Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "<:" mean in Scala?

Tags:

scala

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.

like image 353
deltanovember Avatar asked Jul 26 '11 10:07

deltanovember


People also ask

What is the meaning of => in Scala?

=> 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 .

What does :+ mean in Scala?

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.

What is [+ A in Scala?

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.

What is .type in Scala?

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.


1 Answers

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 } 
like image 188
0__ Avatar answered Sep 29 '22 18:09

0__