"val a:A = new B ", what's the point?

scala, type-inference, types

Solution

It can be useful for:

- Describing the programmer intent (I created a B, but I'm interested only the A behavior)

- Ensuring that you will use only methods defined in A. It will allow to swap the concrete implementation later without having to change much of your code.

- Simplifying the list of auto-completion available when using an IDE or the REPL.

- Forcing an implicit conversion at some point.

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)

Problem

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?

Original source