scala pass type parameter function as a parameter of another function

牧云@^-^@ 提交于 2020-01-16 06:09:49

问题


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 ?


回答1:


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)


来源:https://stackoverflow.com/questions/29180212/scala-pass-type-parameter-function-as-a-parameter-of-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!