After a lot of Java and some Haskell I wanted to have a look at Scala. From the code below, I’m getting this error message
type mismatch; found : List[Nothing] => Option[Nothing] required: List[Int] => Option[Nothing]
I don’t know what I’m doing wrong:
object MyFirstScalaObject {
def main(args: Array[String]) {
lazy val testValues:List[List[Int]] = List((1 to 10).toList, null, List());
println( testFunction(last, testValues));
}
def testFunction[I, O](f : I => O, inputs : List[I]):
List[(I, O)] =
inputs.zip(inputs.map(f));
def last[A](xs:List[A]):Option[A] = xs match {
case x::Nil => Some(x);
case _::xs => last(xs);
case _ => None;
}
}
Thanks for any advice.
Cheers,
because of the way type inference works in scala, it is unable to determine the what the type parameter to
lasthas to be, so it has to take the overly conservative fallback guess that it isNothing.You can explicitly specify the types when you call
testFunction:or you can document more fully the relationship between the type parameters in the
testFunctiondeclaration, which will give the type inferencer more information:This explicitly says that I and O are type constructors (kind * -> *), now that the input/output types of f are more specific, the inferencer can correctly infer that the A parameter to the the last function must be Int.