2017-09-20 118 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的变种我更改代码有点