I am surfing through Scala for the Impatient, but unfortunately it assumes previous Java experience and an understanding of how [T] is used here:
object Iterables {
def filter[T](unfiltered: Iterable[T], predicate: T => Boolean): Iterable[T] = {...}
def find[T](iterable: Iterable[T], predicate: T => Boolean): T = {...}
}
The syntax for every instance of [T] and T is quite confusing here. What significance does it have when it’s listed directly after the function name, such as filter[T]. I understand in the parameters list, we’re looking for an Iterable of type T. But if T is a type, what does predicate: T => Boolean mean?
Type Parametric Methods
A method in scala can accept one or more
type parameters, just like aclass,objectortraitdoes.In this case it means that the same method can be called for a type
Twhich can vary from call to call, but that have to be consistent within the definition.Let’s use for example
The method expects you to pass:
– an
IterableofTs (unfiltered)– a function that transforms a
Tto aBoolean(predicate)and the result will be another
IterableofTs.The method will then iterate on the
unfilteredobject and for each element apply thepredicate, to decide if it must be filtered or not.The resulting
Iterableonly contains the elements satisfying thepredicate(i.e. thosetfor whompredicate(t)returnstrue)You can call filter for any type
T, with the constraint that it must be consistent fo all parameters and the result type.examples