Select all correct ways to extend following traits.
trait QuizfulOne {
  var value: String
}

trait QuizfulTwo {
  def value: String
}
Explanation
A def can be implemented by either of a def, a val, a lazy val or an object. So it's the most abstract form of defining a member. Since traits are usually abstract interfaces, saying you want a val is saying how the implementation should do. If you ask for a val(the same is for a var), an implementing class cannot use a def.
Theory
  • It's a bad practice to declare abstract vars in abstract classes or traits. Do not do this:
    trait Foo {
      var value: String
    }
    
    Instead, prefer to declare abstract things as def:
    trait Foo {
      def value: String
    }
    
    // can then be overridden as anything
    class Bar(val value: String) extends Foo
    
    The reason has to do with the imposed restriction - a var can only be overridden with a var. The way to allow freedom to choose on inheritance is to use def for abstract members. And why would you impose the restriction to use a var on those that inherit from your interface. def is generic so use it instead.
    Read more.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes