Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
  }
}
like image 292
Rahul Wagh Avatar asked Feb 17 '26 04:02

Rahul Wagh


2 Answers

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)
like image 191
Krzysztof Atłasik Avatar answered Feb 19 '26 04:02

Krzysztof Atłasik


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
like image 33
Mario Galic Avatar answered Feb 19 '26 03:02

Mario Galic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!