[英]Scala Error: type mismatch found :(Int, Int) => Int required: Ordering[Int]
While running the following code in scala, the error Type mismatch is throwing 在Scala中运行以下代码时,抛出错误Type不匹配
private def currentOrd: Ordering[Int] =
if (isAscending) (x: Int, y: Int) => x+y
else (x: Int, y: Int) => y - x
Just what the error says: your code says it's supposed to return Ordering[Int]
, but it returns a function. 错误的含义:您的代码说应该返回Ordering[Int]
,但是它返回一个函数。 In Scala 2.12 a function literal can be automatically converted to a single-abstract-method trait like Ordering
(and your code will compile), but not in 2.11 or before. 在Scala 2.12中,函数文字可以自动转换为像Ordering
这样的单抽象方法特征(您的代码将被编译),但不能在2.11或更早版本中转换。
Separately from that, (x: Int, y: Int) => x+y
is quite unlikely to be right; 与此不同的是, (x: Int, y: Int) => x+y
不太可能是正确的。 if you meant (x: Int, y: Int) => x - y
then a better way to write it (which works in previous versions too) is 如果您的意思是(x: Int, y: Int) => x - y
那么编写它的更好方法(在以前的版本中也适用)是
if (isAscending) Ordering.Int else Ordering.Int.reverse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.