0

As i understand vals are immutable in Scala. However in case of inheritance we can override a val defined in the base class. If the val member already got created when the base class was constructed then how can derived class override it? What am i missing?

class Animal ()
{
    val talk: String = "Ha Ha!"
}

class Dog extends Animal
{
    override val talk = "Woof Woof!"
}

class Cat extends Animal

@main def mainFn() = {
    var happyAnimal = new Animal()
    println(happyAnimal.talk)

    happyAnimal = new Dog()
    println(happyAnimal.talk)

    happyAnimal = new Cat()
    println(happyAnimal.talk)

}

Output

Ha Ha! Woof Woof! Ha Ha!

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Player
  • 378
  • 2
  • 7
  • I tried to create a function in Dog def hello () = { println("am inside hello of Dog") println(super.talk) } I get an error -- "super may be not be used on val talk" – Player Feb 19 '23 at 08:10
  • 4
    `val` is a run-time restriction, overriding happens at compile time. `talk` will only ever have a single, immutable value at run time, but that value is selected at compile time via inheritance and the `override` – Tim Feb 19 '23 at 08:25
  • 1
    You can think that `val`s become immutable once their value is computed and `override val` just change how this value is computed. Or that it is a pragmatic trade-off of a language to allow overriding val but only in classes and only during initialization and only in one specific way, because it might feel a bit inconsistent but in some cases is very useful and hard to do things differently. – Mateusz Kubuszok Feb 22 '23 at 09:37

0 Answers0