Scala Type inference with parametric function

I studied Scala these days, and today I have run into a problem that I cannot understand.

Suppose we have the following definition of a parametric function:

def filter[T](source: List[T], predicate: T=>Boolean): List[T] = {
    source match {
        case Nil => Nil
        case x::xs => if(predicate(x)) x::filter(xs, predicate)
                  else filter(xs, predicate)
    }
}

Now this works fine if I call it like this:

filter(List(1,2,3,4,5,6), ( (n:Int) => n % 2 == 0))

But if you remove the type tag, Scala appears cannot conclude that the type T is Int.

filter(List(1,2,3,4,5,6), ( n => n % 2 == 0))

So, I am forced to provide explicit type information in this call.

Does anyone know why Scala cannot infer type T in this call. The list is apparently an Ints list, I don’t understand why it cannot conclude that the type n is also Int.

+5
source share
2 answers

Scala , , T Int , . , , :

def filter[T](source: List[T])(predicate: T => Boolean): List[T] =
  source match {
    case Nil => Nil
    case x :: xs =>
      if (predicate(x))
        x :: filter(xs)(predicate)
      else
        filter(xs)(predicate)
  }

:

scala> filter(List(1, 2, 3, 4, 5, 6))((n => n % 2 == 0))
res0: List[Int] = List(2, 4, 6)

. .

+8

, :

def filter[T](source: List[T])(predicate: T=>Boolean): List[T] = {
    source match {
        case Nil => Nil
        case x::xs => if(predicate(x)) x::filter(xs)(predicate)
                   else filter(xs)(predicate)
    }
}

filter(List(1,2,3,4,5,6))(_ % 2 == 0)

, scala.

+1

All Articles