Will the following code compile?
abstract class Element {
  def contents: Array[String]
}

class ArrayElement(conts: Array[String]) extends Element {
  val contents: Array[String] = conts
}
Explanation
Get an explanation when it's available:
Theory
  • In Scala, fields and methods belong to the same namespace. This makes it possible for a field to override a parameterless method. For instance, you could change the implementation of contents in class ArrayElement from a method to a field without having to modify the abstract method definition of contents in class Element
    abstract class Element {
      def contents: Array[String]
    }
    
    class ArrayElement(conts: Array[String]) extends Element {
      val contents: Array[String] = conts
    }
    
    Field contents (defined with a val) in this version of ArrayElement is a perfectly good implementation of the parameterless method contents (declared with a def) in class Element.
    Source: Overriding methods and fields

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback