Search code examples
scalareturn-valuescala-option

Scala returning option value


The problem is that I'd like this function to return option value (in form of Option[None]) or Option[something], but it only returns a Unit. What am I missing?

  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
       
     }

Solution

  • You are missing = before the first {. Methods defined without = always return Unit. Note that this syntax is actually deprecated precisely because this is a common error: https://issues.scala-lang.org/browse/SI-7605.