scala - 如何使用 > <<= >= 作为函数?

标签 scala

我需要定义一些案例类,如下所示:

case class Gt(key: String, value: Any) extends Expression {
  def evalute[V, E](f: String => Any) = {
    def compare(v: Any): Boolean = {
      v match {
        case x: Number => x.doubleValue > value.asInstanceOf[Number].doubleValue
        case x: Array[_] => x.forall(a => compare(a))
        case x => x.toString > value.toString
      }
    }
    compare(f(key))
  }
}

我不喜欢重复 > < >= 和 <=

我也试过这个:
trait Expression {
  def evalute[V, E](f: String => Any) = true

  def compare(v: Any, value: Any, cp: (Ordered[_], Ordered[_]) => Boolean): Boolean = {
    v match {
      case x: Number => cp(x.doubleValue, value.asInstanceOf[Number].doubleValue)
      case x: Array[_] => x.forall(a => compare(a, value, cp))
      case x => cp(x.toString, value.toString)
    }
  }
}
case class Gt(key: String, value: Any) extends Expression {
  def evalute[V, E](f: String => Any) = {
    compare(f(key), value, ((a, b) => a > b))
  }
}

但这不起作用:(
error: could not find implicit value for parameter ord: scala.math.Ordering[scala.math.Ordered[_ >: _$1 with _$2]]
compare(f(key), value, ((a, b) => a > b))

有没有办法在scala中将运算符作为函数传递?

最佳答案

(a, b) => a > b工作正常。你的问题在于类型。

  • 什么是VEevalute[V, E]应该是?
  • 你通过它(a, b) => a > b作为参数 cp: (Ordered[_], Ordered[_]) => Boolean .所以你有 a: Ordered[_]b: Ordered[_] .与 a: Ordered[X] forSome {type X} 相同和 b: Ordered[Y] forSome {type Y} .对于这些类型,a > b没有意义。
  • 关于scala - 如何使用 > <<= >= 作为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4048713/

    相关文章:

    Java/Scala - 将 xml 转换为 json

    scala - 如何根据条件(组中的值)更新列?

    scala - 使SBT任务依赖于OneJar任务

    scala - elastic4s:反序列化搜索结果

    java - 使用 gm4java 在单个进程中进行多个图像操作

    scala - Scala的 “powerful”类型系统是什么?

    Scala 延续 : many shifts in sequence

    scala - redis ZADD <keys>在redis集群环境下是否一致?

    scala - 如何在 IntelliJ IDEA 14.0.x 中定义/安装 Scala Facet?

    scala - 使用 shapeless 从案例类中提取数据,修改它,并重新创建案例类