ericky ericky - 1 year ago 57
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 = Char) => f(r: Char))

Which works fine (if not a bit verbose):

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


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


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?



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


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 Source

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] =
testerA: [A](l: List[A])(f: A => A)List[A]

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