相关疑难解决方法(0)

如何使这个first-not-null-result函数更优雅/简洁?

getFirstNotNullResult执行函数列表,直到其中一个函数返回非null值.如何更优雅/简洁地实现getNotNullFirstResult?

object A {
  def main(args: Array[String]) {
    println(test());
  }

  def test(): String = {
    getFirstNotNullResult(f1 _ :: f2 _ :: f3 _ :: Nil);
  }

  def getFirstNotNullResult(fs: List[() => String]): String = {
    fs match {
      case head::tail => 
        val v = head(); 
        if (v != null) return v;
        return getFirstNotNullResult(tail);

      case Nil => null
    }
  }

  // these would be some complex and slow functions; we only want to execute them if necessary; that is, if f1() returns …
Run Code Online (Sandbox Code Playgroud)

scala

3
推荐指数
3
解决办法
3064
查看次数

标签 统计

scala ×1