|
define a trait named `Option` <parametrized with another type> A <(think of the List type that can be parametrized with another type, e.g. Booleans)>. The + is there to indicate covarience, i.e. that for a type B that extends A, Option[B] can also be thought of as a subtype of Option[A] (e.g. a list of integers is a subtype of a list of floats). the Option type defines a method `bind` (I'll come back to the type B) which takes a function f that takes something of type A and returns something of type Option[B], no matter what B is (Scala makes you declare the type parameters you use in a function's arguments in the beginning (after its name)). I found that explaining bind works best with a more familiar type like List. if we have a type List of A's, and to simplify further, let's say that A is Int, so we have a List of Ints, then bind is a function that applies its argument, the latter being a function itself, on all its elements, and merging the resulting lists together.
Suppose we pass the function `f` that for an Int returns the int itself and its double to the bind function of the following list: [1, 10, 100] In the first step, the function f is applied to all the list elements:
[[1, 2], [10, 20], [100, 200]]
Than flattens it so we end up with:
[1, 2, 10, 20, 100, 200]. |