2017-09-20 116 views
0

prolbem是我希望這個函數返回選項值(以Option [None]的形式)或Option [something],但它只返回一個Unit。我錯過了什麼?斯卡拉返回選項值

def intersection(another: Interval){ 
    var test: Option[Interval] = None 
    if (this.isLaterThan(another) || another.isLaterThan(this)){ 
     test 
    } 
    else { 
     val a = this.start.later(another.start) 
     val b = this.end.earlier(another.end) 
     test=Some(new Interval(a, b)) 
     test 

    } 

回答

0

您應該指定類型它返回

def intersection(another: Interval): Option[Interval] = { 
    if (this.isLaterThan(another) || another.isLaterThan(this)){ 
     None 
    } 
    else { 
     val a = this.start.later(another.start) 
     val b = this.end.earlier(another.end) 
     Some(new Interval(a, b)) 

    } 
} 

儘量不使用Scala的變種我更改代碼有點