2

As shown in below code parameters in primary constructor are defined with default values and val it means values of those parameters should not change. But still why the values changing while initializing the constructor

//Why values of Aname and Cname is getting overwritten      
class GFG(val Aname: String = "Ank", val Cname: String = "Constructors") {
  def display() = {
    println("Author name: " + Aname)
    println("Chapter name: " + Cname)

  }
}
//object main
object Main {
  def main(args: Array[String]) = {
    var obj = new GFG("a", "b")
    obj.display()
  }
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Rahul Wagh
  • 281
  • 6
  • 20

2 Answers2

5

With

class GFG(val Aname: String = "Ank", val Cname: String = "Constructors")

you're creating a class with a constructor with default parameters. These values will be used only if you don't provide them explicitly. That means you can do:

new GFG("a", "b") //both parameters provided, no default values are used -> GFG(a,b)

new GFG("a") //only first parameter provided, second default value is used -> GFG(a,Constructors)

new GFG() // no parameters provided explicitly, only default values are used -> GFG(Ank,Constructors)

As you can see that way, you can't use the default value for Aname but explicit for Cname, but it's possible if you used named parameters:

new GFG(Cname = "b") // GFG(Ank, b)
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
  • 1
    So does that means only within the constructor body you are not allowed to change the value of those parameters? – Rahul Wagh Jul 08 '19 at 11:45
  • 3
    Since they're **vals** you cannot reassign them. The point is, that here `val Aname: String = "Ank"` you're not really assigning **val**. You are just providing *default* value in case it is not passed explicitly during method invocation. – Krzysztof Atłasik Jul 08 '19 at 11:48
3

Vals can be assign a value during initialisation but cannot be changed after initialisation, for example

var obj = new GFG("a", "b") // ok
obj.Aname // res0: String = a
obj.Aname = "foo" // Error: reassignment to val
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • The output of above program is Author name: a Chapter name: b -- my question is I have declared both parameters with val and default values then why those values are not coming in output and why they are getting overwritten – Rahul Wagh Jul 08 '19 at 11:40
  • 1
    Default parameters are used only if explicit arguments are not passed in. When you do `new GFG("a", "b")`, then you explicitly pass in `"a"` and `"b"`, thus defaults are not used. – Mario Galic Jul 08 '19 at 11:45