【问题标题】:How to assign one lambda expression object to another?如何将一个 lambda 表达式对象分配给另一个?
【发布时间】:2019-06-08 13:22:20
【问题描述】:

我有这种代码,我想将其中一个 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 设置为真或假。 这是部分有效的代码。

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

我想同时设置opSpecBoolVal 为真或假。

【问题讨论】:

    标签: scala lambda


    【解决方案1】:

    试试

    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
    

    【讨论】:

    • Prototype.scala:7: error: ')' expected but ':' found. val earlyExitCheck: (x: Int, y: Int) =&gt; Boolean = operatorType match { ^ 关于这个错误有什么想法吗?
    • val earlyExitCheck: (Int, Int) =&gt; Boolean = ...这样的类型中删除xy
    猜你喜欢
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 2021-05-02
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2016-06-24
    相关资源
    最近更新 更多