在scala中,函数即对象,我们可以通过val来定义函数,
例如绝对值函数:def abs(x:Double)=if(x>0) x else -x
也可以如下定义:
val abs=(x:Double)=>{ if(x>0) x else -x }
但是并非所有的场合都可以如此替代,
来看一个示例:
object Words { private val filePath = "/tmp/words.txt" val getWords1 = read() def getWords2 = read() val getWords3 = () => read() def write(content: Traversable[String]) = { import com.flute.common.Implicits._ content.saveToFile(filePath) } private def read() = { scala.io.Source.fromFile(filePath).mkString } }
测试代码:
object Test{ def main(args: Array[String]) { Words.write(Traversable("scala", "java", "python")) println(Words.getWords1) println(Words.getWords2) println(Words.getWords3()) Words.write(Traversable("js", "c++")) println("after update words...") println(Words.getWords1) println(Words.getWords2) println(Words.getWords3()) } }
运行结果:
scala
java
python
scala
java
python
scala
java
python
after update words...
scala
java
python
js
c++
js
c++
可以发现,当修改文件内容后,调用getWords1返回的结果并未更新,
实际上,这里的getWords1是一个成员常量,而getWords3,“=”后面的部分是一个匿名函数,getWords3是匿名函数的别名。