Scala-Lazy
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala-Lazy相关的知识,希望对你有一定的参考价值。
在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>
以上是关于Scala-Lazy的主要内容,如果未能解决你的问题,请参考以下文章