Understanding Case class and Traits in Scala

前端 未结 3 584
一生所求
一生所求 2021-02-08 02:53

I have a simple trait as defined below:

trait MyTrait {

  def myStringVal: String

}

My case class which implements this trait is as below:

3条回答
  •  清歌不尽
    2021-02-08 03:16

    Scala case classes have a plenty of boilerplate implemented for you, and having all the constructor parameters automatically exposed as vals is one of these things.

    If you try avoiding vals in a regular class, like that:

    trait MyTrait {
      def myVal: String
    }
    
    class MyClass(myVal: String) extends MyTrait
    

    Compiler will show you the error message, that MyClass has to be abstract, as it does't override myVal method, but adding val or var to the class constructor parameter will solve the issue.

提交回复
热议问题