Ravi Ravi - 1 month ago 14
Scala Question

Scala - what is this - case class extends trait

I am understanding my existing project, Few things I am not able to understand could you please help me:

trait PeriodA {
def start: Long
def stop: Long
def description: String
def manageTo: String
}

case class PeriodEntity(
start: Long,
stop: Long,
description: String,
manageTo: String)
extends PeriodA


could you please explain, what happens here:

Answer

Step by step:

  • trait PeriodA { – definition of a trait (which is roughly an interface – for further understanding please read spec)

  • def start: Long def stop: Long def description: String def manageTo: String – definition of 'on-call' evaluated properties of trait. You could consider them as Java getFieldName functions.

  • case class PeriodEntity definition of a 'case class' which is slightly more complicated than general one. In few words, that definition makes compiler implicitly add valprefix to each so-called 'element' (field) of the definition. It also define the companion object with apply/unapply functions pair, which comes in handy in case you want to use pattern matching, but that's out of the current topic. Case classes specification

  • start: Long, stop: Long, description: String, manageTo: String – definition of both constructor parameters and class fields, which called 'elements'. As far as compiler implicitly mark elements with val prefix, they should be considered as immutable. As it was mentioned previously, they could be considered as get accessors.

  • extends PeriodA - declares that class PeriodEntity mixins (implements) PeriodA interface. As far as case class elements are implicitly considered as val's by compiler there is no need to explicitly implement or override abstract PeriodA methods – compiler will treat elements as a default implementations for you.