我有这样的代码:
def fn(operatorType: (Int, Int) => Boolean) {
operatorType match {
case ((Int, Int) => _ == _) => //dosomething
case ((Int, Int) => _ > _) => //dosomething
}
}
fn((a: Int, b: Int) => a > b)
fn((a: Int, b: Int) => a == b)
是否可以知道已将哪种布尔表达式传递给该方法?还是有更好的方法来实现相同的逻辑?我必须严格将方法保留为lambda表达式的一个参数。
答案 0 :(得分:2)
这是@LuisMiguelMejiaSuarez建议的示例:
sealed trait Op extends ((Int, Int) => Boolean)
case object Equal extends Op {
def apply(a: Int, b: Int): Boolean = a == b
}
case object GreaterThan extends Op {
def apply(a: Int, b: Int): Boolean = a >= b
}
case object LessThan extends Op {
def apply(a: Int, b: Int): Boolean = a <= b
}
case object NotEqual extends Op {
def apply(a: Int, b: Int): Boolean = a != b
}
def fn(operatorType: Op) =
operatorType match {
case Equal => //do something with Equal.apply
case GreaterThan => //do something with GreaterThan.apply
case LessThan => //do something with LessThan.apply
case NotEqual => //do something with NotEqual.apply
}
fn(Equal)