Jade Tang
Jade Tang

Reputation: 319

scala pass type parameter function as a parameter of another function

Suppose,I have a function, take two values and a function as parameters.

def ls[S](a: S, b: S)(implicit evl: S => Ordered[S]): Boolean = a < b
def myfunction[T](a: T, b: T, f:(T,T)=>Boolean) = {

  if (f(a, b)) {
    println("is ok")
  }
  else {
    println("not ok")
  }
}

myfunction(1, 2, ls)

the IDE don't give any error message,but when I try to compile and run,the compliter give this message:

    Error:(14, 19) No implicit view available from S => Ordered[S].
myfunction(1, 2, ls);}
                 ^

So,is there a way to pass type parameter function as a parameter of another function ?

Upvotes: 1

Views: 281

Answers (1)

kpbochenek
kpbochenek

Reputation: 469

Firstly this works:

myfunction[Int](1, 2, ls)
myfunction(1, 2, ls[Int])

From my understanding the Scala compiler tries to resolve type T of myfunction.

It finds first and second argument and is happy to assign it to Int (or anything that is its supertype) as the best match.

But the third argument says that it can get anything as a parameter! Then the Scala compiler must comply and decides that T will be Any. Which causes S be of type Any and there is no implicit view Any => Ordered[Any]

You must not think of myfunction as defining a type for ls but rather ls defining what type T can be.

Which is why this will work as you will already know what type of f you want:

def myfunction[T](a: T, b: T)(f:(T,T)=>Boolean) = {
...
}
myfunction(1, 2)(ls)

Upvotes: 2

Related Questions