I'm looking at p. 469 of "Programming in Scala" Second Edition. There is a line of code that reads:
type Currency <: AbstractCurrency
I cannot decipher what this means.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.
It declares the class to be covariant in its generic parameter. For your example, it means that Option[T] is a subtype of Option[S] if T is a subtype of S . So, for example, Option[String] is a subtype of Option[Object] , allowing you to do: val x: Option[String] = Some("a") val y: Option[Object] = x.
Scala is a statically typed programming language. This means the compiler determines the type of a variable at compile time. Type declaration is a Scala feature that enables us to declare our own types.
It means an abstract type member is defined (inside some context, e.g. a trait or class), so that concrete implementations of that context must define that type. However, there is a constraint that this type (Currency
) must actually be a subtype of AbstractCurrency
. That way the abstract context can operate with Currency
, knowing that it understands every operation of AbstractCurrency
.
trait AbstractCurrency { def disappearInGreece(): Unit } abstract class Economy { type Currency <: AbstractCurrency def curr: Currency // can call disappear... because `Currency` // is an `AbstractCurrency` def shake(): Unit = curr.disappearInGreece() }
Trying to define Currency
without constraints:
trait RadioactiveBeef class NiceTry(val curr: RadioactiveBeef) extends Economy { type Currency = RadioactiveBeef }
Fails. With constraints ok:
trait Euro extends AbstractCurrency class Angela(val curr: Euro) extends Economy { type Currency = Euro }
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