Search code examples
scalaimmutabilitydefault-value

Primary constructor parameter declared using val allows to change the value


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()
  }
}

Solution

  • 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)