Why does ensuring work only on else?
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 a开发者_如何学JAVAn 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?
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)
精彩评论