Home > Software engineering >  override lazy val in constructor / scala
override lazy val in constructor / scala

Time:05-26

I want to override a lazy val in the constructor in scala. Any ideas how to do this ? I tried the following but i get

'lazy' modifier not allowed here, use call-by-name parameter instead

  class Dog(override lazy val creatureType: String) extends Animal {

// valid
//  override lazy val creatureType: String = "Dog"
// but i want to override it in the constructor directly 

}

The Parent class :

  class Animal {
 lazy val creatureType: String = "unknown"
  }

CodePudding user response:

Something like this should work:

   class Dog(foo: => String) extends Animal {
     override lazy val creatureType = foo
   }
  • Related