ericky ericky - 3 months ago 7
Scala Question

Scala type mis-match: Nothing => Nothing?

First stackoverflow question and new to Scala. Trying to understand polymorphic types with this example I wrote:

def identFun[A](a: A): A = a

def testerChar(l: List[Char], f: Char => Char): List[Char] = {
val li = l.map((r: Char) => f(r: Char))
li
}


Which works fine (if not a bit verbose):

scala> testerChar(List('a','b','c'), identFun)
res49: List[Char] = List(a, b, c)


However:

def testerA[A](l: List[A], f: A => A): List[A] = {
val li = l.map((r: A) => f(r: A))
li
}


Yields:

scala> testerA(List('a','b','c'), identFun)
<console>:14: error: type mismatch;
found : Nothing => Nothing
required: Char => Char
testerA(List('a','b','c'), identFun)


What am I missing that would allow "testerA" to return identities for any type passed to it?

Thanks!

Tried:

def testerA[A](l: List[A])( f: A => A): List[A] = {
val li = l.map((r: A) => f(r: A))
li
}


Got:

scala> testerA(List('a','b','c'), identFun)
<console>:14: error: too many arguments for method testerA: (l: List[A])(f: A => A)List[A]
testerA(List('a','b','c'), identFun)

Answer

It turns out you can also get what you're after if you simplify things.

scala> def identFun[A](a: A): A = a
identFun: [A](a: A)A

scala> def testerA[A](l: List[A])(f: A => A): List[A] = l.map(f)
testerA: [A](l: List[A])(f: A => A)List[A]

scala> testerA(List('a','b','c'))(identFun)
res5: List[Char] = List(a, b, c)