Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding types in [ ] brackets in function definition

Tags:

scala

Welcome everyone,

I am actually learning scala through studying "Functional Programming in Scala" book, and in this book authors are parametrizing functions with adding types in [ ] brackes following name of the function like:

def sortList[A](xs: List[A]): List[A] = ...

What is reason for doing that? Compiler cant infer it by itself from parameters? Or am i missing something?

like image 342
Gawrosz Avatar asked Feb 13 '15 20:02

Gawrosz


1 Answers

In the specific instance above, A is the type that the sortList function will work on. In other words, it will take a List containing objects of type A and sort them, returning a new List with objects of type A.

You would use it as follows:

val list = 10::30::List(20)
val sortedList = sortList(list)

The scala compiler will detect that the type of the List being passed in is a list of Int and understand that the "A" in the declaration is the type of the List being passed in.

The type has to be known at compile time, but scala is very good at inferring the types, and in the example above, it can see that the type of the list being passed in is a list of Int

It is important to note that the type is initially inferred when the List is created to be of type List[Int] and then the compiler can also see later, when the list is passed to the sortList function, that the type of the List being passed in to sortList is List[Int]

Here are some additional examples that I threw together to show more. If you run these commands in the Scala command line or using a Scala Eclipse worksheet you'll see what is going on. The only additional thing here really is that it also shows you can apply the type to sortList without other parameters to make it specific to Ints rather than applicable to all types.

/* Declare a List[Int] and List[String] for use later */
val list = 10::30::List(20)
val stringList = "1"::"2"::List("3")

/* Doesn't actually sort - just returns xs */
def sortList[A](xs: List[A]): List[A] = xs

/* Sort both lists */
sortList(list)
sortList(stringList)

/* Create a version of sortListInt which just works on Ints */
def sortListInt = sortList[Int] _

/* Sort the List[Int] with the new function */
sortListInt(list)

/* fails to compile - sortListInt is a
version of sortList which is only applicable to Int */
sortListInt(stringList)
like image 137
Mike Curry Avatar answered Sep 30 '22 00:09

Mike Curry