如何将一个Lambda表达式对象分配给另一个?

时间:2019-06-08 13:22:20

标签: scala lambda

我有这样的代码,我想在一个对象中存储一个lambda表达式。

var opSpecBoolVal = false
val equalCheck = (x: Int, y: Int) => x == y
val greaterthanCheck = (x: Int, y: Int) => x > y
val lessthanCheck = (x: Int, y: Int) => x < y
val notEqualCheck = (x: Int, y: Int) => x != y

operatorType match {
   case "_equal" => opSpecBoolVal = false; exitCheck = equalCheck; 
   case "_greaterthan" => opSpecBoolVal = true; exitCheck = greaterthanCheck; 
   case "_lessthan" => opSpecBoolVal = false; exitCheck = lessthanCheck; 
   case "_notequal" => opSpecBoolVal = true; exitCheck = notEqualCheck;
}
exitCheck(10, 20)

代码检查operatorType字符串,如果它与任何模式匹配,则将opSpecBoolVal设置为某个值true或false,并将一个lambda表达式分配给另一个对象,这就是我正在寻找的地方将lambda对象分配给其他对象的难度。主要座右铭是不让其余代码知道operatorType字符串包含什么,而是通过传递两个参数并获得布尔结果直接使用exitCheck

我正在研究一种解决方案,其中只有exitCheck个部分有效,但无法将opSpecBoolVal设置为true或false。 这是部分起作用的代码。

val exitCheck = operatorType match {
   case "_equal" => equalCheck; 
   case "_greaterthan" => greaterthanCheck; 
   case "_lessthan" => lessthanCheck; 
   case "_notequal" => notEqualCheck;
}

我想同时将opSpecBoolVal设置为true或false。

1 个答案:

答案 0 :(得分:5)

尝试

val exitCheck: (Int, Int) => Boolean = operatorType match {
  case "_equal" =>
    opSpecBoolVal = false
    _ == _

  case "_greaterthan" =>
    opSpecBoolVal = true
    _ > _

  case "_lessthan" =>
    opSpecBoolVal = false
    _ < _

  case "_notequal" =>
    opSpecBoolVal = true
    _ != _
}

输出

val operatorType = "_greaterthan"
exitCheck(10, 20) // res0: Boolean = false

为避免将var opSpecBoolVal设置为副作用,请尝试使用类似的替代纯实现方式

type OperatorType = String
type Operator = (Int, Int) => Boolean
type IsSpecialOp = Boolean

val toOp: OperatorType => (Operator, IsSpecialOp) =
{
  case "_equal" => (_ == _, false)
  case "_greaterthan" => (_ > _, true)
  case "_lessthan" => (_ < _, false)
  case "_notequal" => (_ != _, true)
}

输出

val (exitCheck, opSpecBoolVal) = toOp("_greaterthan")
exitCheck(10, 20) // res0: Boolean = false
opSpecBoolVal // res1: IsSpecialOp = true