标签:
在Scala中,提供了lazy值的特性,也就是说,如果将一个变量声明为lazy,则只有在第一次使用该变量时,变量对应的表达式才会发生计算。这种特性对于特别耗时的计算操作特别有用,比如打开文件进行IO,进行网络IO等。
scala> import scala.io.Source._ import scala.io.Source._ scala> lazy val lines = fromFile("C:\\Users\\Administrator\\Desktop\\test.txt").mkString lines: String = <lazy> scala> println(lines) def sayHello(name:String,age:Int)={ if(age >18){ printf("Hi , %s , you are big boy !!!",name) age }else{ printf("Hi , %s , you are little boy !!!",name) age } }
scala> lazy val lines = fromFile("C:\\Users\\Administrator\\Desktop\\test2222.txt").mkString lines: String = <lazy> scala> println(lines) java.io.FileNotFoundException: C:\Users\Administrator\Desktop\test2222.txt (系统找不到指定的文件。) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at scala.io.Source$.fromFile(Source.scala:91) at scala.io.Source$.fromFile(Source.scala:76) at scala.io.Source$.fromFile(Source.scala:54) at .lines$lzycompute(<console>:16) at .lines(<console>:16) ... 33 elided scala> val lines = fromFile("C:\\Users\\Administrator\\Desktop\\test2222.txt").mkString java.io.FileNotFoundException: C:\Users\Administrator\Desktop\test2222.txt (系统找不到指定的文件。) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at scala.io.Source$.fromFile(Source.scala:91) at scala.io.Source$.fromFile(Source.scala:76) at scala.io.Source$.fromFile(Source.scala:54) ... 33 elided scala>
标签:
原文地址:http://www.cnblogs.com/thinkpad/p/5628465.html