Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 694
Andriy Drozdyuk Avatar asked Apr 30 '11 18:04

Andriy Drozdyuk


People also ask

What is the purpose of work with others?

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.


1 Answers

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)
like image 198
sepp2k Avatar answered Oct 23 '22 06:10

sepp2k