码迷,mamicode.com
首页 > 其他好文 > 详细

Scala-Lazy

时间:2016-06-29 23:40:31      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:

在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

标签:

原文地址:http://www.cnblogs.com/thinkpad/p/5628465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!