Scala Rank-1 Polymorphism

The following code snippet from twitter Scala school:

Scala has rank-1 polymorphism. Roughly speaking, this means that there are some types of concepts that you would like to express in Scala that are "too general" for the compiler to understand. Suppose you have a function:

def toList[A](a: A) = List(a)

      

which you wanted to use in general:

def foo[A, B](f: A => List[A], b: B) = f(b)

      

This will not compile because all type variables must be captured in the calling site. Even if you nail the type B

,

def foo[A](f: A => List[A], i: Int) = f(i) // Line 1

      

... you get a type mismatch.

Why is line 1 not working? Type B is known. Why is this compilation not being performed?

+3


source to share


1 answer


scala> def toList[A](a:A) = List(a)
toList: [A](a: A)List[A]

scala> def foo[A, B](f: A => List[A], b: B) = f(b)
<console>:10: error: type mismatch;
 found   : b.type (with underlying type B)
 required: A
       def foo[A, B](f: A => List[A], b: B) = f(b)

      

This line doesn't compile because you are passing a value of a type B

when the function expects a value of a type A

.



def foo[A](f: A => List[A], i: Int) = f(i) // Line 1

      

For this line, you will need to introduce an implicit conversion from type Int

to type A

.

+5


source







All Articles