Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 437
Ashkan Kh. Nazary Avatar asked Jun 08 '12 06:06

Ashkan Kh. Nazary


2 Answers

It can be useful for:

  1. Describing the programmer intent (I created a B, but I'm interested only the A behavior)
  2. 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.
  3. Simplifying the list of auto-completion available when using an IDE or the REPL.
  4. 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)
like image 145
paradigmatic Avatar answered Oct 01 '22 22:10

paradigmatic


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.

like image 33
aioobe Avatar answered Oct 01 '22 22:10

aioobe