scala中无法访问的代码

时间:2016-11-04 01:01:29

标签: scala function unreachable-code

val LIST = scala.collection.mutable.MutableList[String]()
  val filterF = new Function[Path, Boolean] {
    def apply(x: Path): Boolean = {
      println("looking into  " + x)
      val flag = if (x.toString.split("/").last.split("_").last.toLong < System.currentTimeMillis) {
        println("considered " + x)
        LIST += x.toString
        return true
      } else {
        println("NOT considered " + x)
        return false
      }
      return flag
    }
  }

我正在尝试更新函数LIST中的外部变量filterF。但问题是在println("looking into "+x)之后 其余代码无法访问。

 val flag = if (x.toString.split("/").last.split("_").last.toLong < System.currentTimeMillis) {
        println("considered " + x)
        LIST += x.toString
        return true
      } else {
        println("NOT considered " + x)
        return false
      }
      return flag

我无法理解为什么这段代码无法访问。代码中是否有一些字符实际上是这个原因?

2 个答案:

答案 0 :(得分:2)

这导致flag val 而不是 def ,但您的声明正在使用return返回 true false return关键字仅适用于非功能方法。

正确的方法可能是:

val flag = if (x.toString.split("/").last.split("_").last.toLong < System.currentTimeMillis) {
  println("considered " + x)
  LIST += x.toString
  true
}
else {
  println("NOT considered " + x)
  false
}

答案 1 :(得分:2)

不要使用return

当你使用return执行控制时,将保留函数,并且返回语句之后的所有代码都将无法访问

返回后的代码将无法访问

def foo: Int = {
 return 1
 2 + 3 //unreachable
}

if if expression

def bar: Int = {
  if (true) {
   return 1
  } else {
   return 2
  }
  1 + 2 //unreachable
}

在Scala中,return语句是可选的,不推荐使用,因为它不考虑函数编码实践。

  

代码块中最后一个表达式的值是Scala中的返回值。因此,不要担心明确的回报,只需将其留给程序

 val flag = if (x.toString.split("/").last.split("_").last.toLong < System.currentTimeMillis) {
    println("considered " + x)
    LIST += x.toString
    true //removed return
  } else {
    println("NOT considered " + x)
    false // removed return 
  }

通过抛出异常或返回值或显式调用exit来暂停程序执行不是功能性的处理方式。不幸的是,Scala确实允许它。但如果你想成为功能世界的好公民。你最好避免它。

避免可变集合

如果您对它有强烈需求,请使用mutable个集合。 immutable集合

具有优势

1)它们是线程安全的。

2)没有错误(意外突变没有意外,没有阻塞)。

3)参考透明度。

4)合理的表现。

使用immutable列表而不是mutable列表。

使用Scala lambda表示法和Syntactic sugar

句法糖是有原因的。语法糖减少了样板代码。这样您的代码看起来更清晰,更清晰,更好。有助于代码可维护性。代码在较长时间内仍然没有错误。

而不是Function1特征使用lambda表示法。

scala> val f = new Function1[String, String] { def apply(str: String): String =  str}
f: String => String = <function1>

scala> val f = {str: String => str}
f: String => String = <function1>

所以你的代码变成了

val paths = List[Path]() //assume you have Paths in it.

val filter = {path: Path => path.toString.split("/").last.split("_").last.toLong < System.currentTimeMillis }

val resultList = paths.filter(filter)