Tutorial by Examples

A nice example of a parameterized type is the Option type. It is essentially just the following definition (with several more methods defined on the type): sealed abstract class Option[+A] { def isEmpty: Boolean def get: A final def fold[B](ifEmpty: => B)(f: A => B): B = if (i...
The return type of a method can depend on the type of the parameter. In this example, x is the parameter, A is the type of x, which is known as the type parameter. def f[A](x: A): A = x f(1) // 1 f("two") // "two" f[Float](3) // 3.0F Scala will use type infe...
Defining the list of Ints trait IntList { ... } class Cons(val head: Int, val tail: IntList) extends IntList { ... } class Nil extends IntList { ... } but what if we need to define the list of Boolean, Double etc? Defining generic list trait List[T] { def isEmpty: Boolean def head:...

Page 1 of 1