I have this kind of code where I want store one of the lambda expression in some object.
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)
code checks operatorType string and if it matches any of the pattern then it sets opSpecBoolVal to some value true or false, and it assign one lambda expression to another object and this is where I am finding difficulty in assigning lambda object to some other object. The main motto is not let rest of the code know what operatorType string contains and directly use exitCheck by passing two argument and obtain a boolean result.
I have worked on one solution in which I got only exitCheck part working but couldn't set opSpecBoolVal to true or false.
Here is the code which partially worked.
val exitCheck = operatorType match {
case "_equal" => equalCheck;
case "_greaterthan" => greaterthanCheck;
case "_lessthan" => lessthanCheck;
case "_notequal" => notEqualCheck;
}
I want to set opSpecBoolVal to true or false at same time.
Try
val exitCheck: (Int, Int) => Boolean = operatorType match {
case "_equal" =>
opSpecBoolVal = false
_ == _
case "_greaterthan" =>
opSpecBoolVal = true
_ > _
case "_lessthan" =>
opSpecBoolVal = false
_ < _
case "_notequal" =>
opSpecBoolVal = true
_ != _
}
which outputs
val operatorType = "_greaterthan"
exitCheck(10, 20) // res0: Boolean = false
To avoid setting var opSpecBoolVal as a side-effect, try an alternative pure implementation like so
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)
}
which outputs
val (exitCheck, opSpecBoolVal) = toOp("_greaterthan")
exitCheck(10, 20) // res0: Boolean = false
opSpecBoolVal // res1: IsSpecialOp = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With