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

this idiom (?) appears quite a few times in the book of stairs:

val b:A = new B

or

val b = new B
val b2:A = b

Also, to try to make some points in the tutorial, why do you want to declare a type different from the intended type?

By the way, any names for this?

+5
source share
2 answers

This may be useful for:

  • Describing the intention of the programmer (I created B, but I'm only interested in the behavior of A)
  • Ensuring that you will only use the methods defined in A. This will replace the concrete later without changing much of your code.
  • Simplify the autocomplete list available when using the IDE or REPL.
  • Forced conversion at some point.

, .

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)
+14

, .

val b:A = new B

, , , A. I.e., , - b:A = new C, .

+10

All Articles