2011-04-30 29 views
9

在Scala中,當我使用確保 PREDEF,它僅適用於一個if-else表達式的其他部分:爲什麼確保只在其他方面工作?

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! 

但我認爲, 「如果其他」 是一個表達式斯卡拉。所以它應該只是返回一個值 - 這又應該傳遞給確保

還是我在這裏困惑一些東西?謝謝。

編輯:在Scala中的編程書的作者使用它,如下所示:

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 

難道他也只適用於這裏其他部分?

回答

17

是的,if-else是一個表達式,但是您將括號括起來的方式只適用ensuringx+1,而不是if-表達式。如果你把ensuring圍繞if右括號之後,它會做你想要什麼:

def evenIt(x:Int) = { 
    if(x % 2 == 0) 
     x + 1 //return odd on purpose! 
    else 
     x + 1 
} ensuring(_ % 2 == 0) 
+1

謝謝!我沒有想到這一點。我已經添加了書中的代碼 - 作者使用此功能的地方。他是否將它應用於那裏的其他部分? – drozzy 2011-04-30 23:19:23

+1

我只是偶然發現了同樣的問題)我認爲是的,在這本書中,它只適用於其他部分,因此只在其他部分進行拓寬。但是我們可以對代碼的不同部分進行不同的確保 – damluar 2011-11-04 10:16:58

相關問題