Is non-local return in Scala new?

前端 未结 2 1044
后悔当初
后悔当初 2020-12-24 14:02

A colleague just showed me this and I was surprised that it compiled at all:

def toUpper(s: Option[String]): String = {
  s.getOrElse(return \"default\").toU         


        
2条回答
  •  盖世英雄少女心
    2020-12-24 14:40

    It's been allowed since forever, more or less. It might look strange there, but there are many places where the reverse would be true. For example:

    // excessive use of braces for the sake of making scopes clearer
    
    def findFirst[A](l: List[A])(p: A => Boolean): Option[A] = {
        for (x <- l) {
            if (p(x)) return Some(x)
        }
        None
    }
    

提交回复
热议问题