this idiom(?) appears quite a few times in the stairway book:
val b:A = new B
or
val b = new B
val b2:A = b
besides trying to make some points in a text book, why would you want to declare a type different than the inferred type of something?
By the way, any names for this?
It can be useful for:
For more complex instantiations, it ensures that the inferred type is the right one. For example
sealed trait Answer
case object Yes extends Answer
case object No extends Answer
scala> val a = List( Yes, Yes, No )
a: List[Product with Serializable with Answer] = List(Yes, Yes, No)
scala> val b: List[Answer] = List( Yes, Yes, No )
b: List[Answer] = List(Yes, Yes, No)
I would argue that it is similar to the idiom of programming against interfaces. By doing
val b:A = new B
you make sure that after that point you're not relying on anything else than the interface provided by A
. I.e., it guarantees that if you ever decide to change to b:A = new C
nothing will break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With