Adding Types to [] Brackets in a Function Definition

Greetings to all

I really learn scala by studying the book Functional Programming in Scala, and in this book, the authors parameterize functions with types in brackets after the function name like:

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

What is the reason for this? The compiler cannot do this on its own from the parameters? Or am I missing something?

+4
source share
2 answers

In the above instance, A is the type 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)

scala , Int , "A" - .

, scala , , - Int

, , List List [Int], , sortList, , sortList, - List [Int]

, , . scala scala Eclipse, , . , , sortList , Ints, .

/* 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)
+2

, , . (, , Java, #).

0

All Articles