In scala, when I use the ensuring predef, it works only on the else part of an if-else expression:
def evenIt(x:Int) = {
if(x % 2 == 0)
x+1 //return odd on purpose!
else{
x + 1
} ensuring( _ % 2 == 0)
}
//Test it:
evenIt(3)
> 4
evenIt(4)
> 5 //<--- ensuring does not catch this!
But I thought that "if-else" was an expression in scala. So it should just return a value - which in turn should be passed to ensuring?
Or am I confusing something here? Thanks.
EDIT: In the book Programming in Scala the author uses it as follows:
private def widen(x: Int) : Element =
if(w <= width)
this
else {
val left = elem(' ', (w - width) / 2, height)
var right = elem(' ', w - width - left.width, height)
left beside this beside right
} ensuring ( w <= _.width
Does he apply it only to else part here?
Research shows that collaborative problem solving leads to better outcomes. People are more likely to take calculated risks that lead to innovation if they have the support of a team behind them. Working in a team encourages personal growth, increases job satisfaction, and reduces stress.
Yes, if-else is an expression, but the way you bracketed it, you only apply ensuring
to x+1
, not to the if
-expression. If you put the ensuring
after the closing brace surrounding the if
, it will do what you want:
def evenIt(x:Int) = {
if(x % 2 == 0)
x + 1 //return odd on purpose!
else
x + 1
} ensuring( _ % 2 == 0)
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