What does it mean when => is inside []?

Viewed 81

Recently I've seen book titled "Scala: Applied Machine Learning". I found this:

type U = List[Fields => Double]

I haven't seen => inside [] in many books. Please explain it for me.

2 Answers

Here are the components of type U = List[Fields => Double]:

  • Fields => Double is a function type
  • List is a type constructor for a collection type
  • type U is a type alias

For example, say we have the following functions

val foo: Int => String = (x: Int) => "hello " + x
val bar: Int => String = (x: Int) => "goodbye " + x
val zar: Int => String = (x: Int) => "greetings " + x

Then we could collect them into a List of Int => String functions like so

List[Int => String](foo, bar, zar)

in the same way we can collect integers into a list

List[Int](1,3,42)

In Scala, we say functions are first class values, meaning we can use them just like any other value, that is pass them in and out of other functions, add them to collections, assign them to variables etc.

type U is a type alias meaning it gives a different name to a type on the right-hand side. We can use it, for example, to simplify a long type name, so instead of writing out List[Int => String] we can just write U:

def qux(c: U): U = c

would be the same as

def qux(c: List[Int => String]): List[Int => String] = c

List[T] is a type constructor meaning when we substitute a concrete type for T, such as Int, or String, or Int => String we get the corresponding types List[Int], List[String], and List[Int => String].

It is a List of functions that take an argument of type Fields and return a Double.

In Java 8 it would be semantically equivalent to List<Function<Fields, Double>>. (Not sure if Scala translates it to that underneath the hood yet).

Related