scala学习笔记-过程、lazy值和异常(6)

过程

在Scala中,定义函数时,如果函数体直接包裹在了花括号里面,而没有使用=连接,则函数的返回值类型就是Unit。这样的函数就被称之为过程。过程通常用于不需要返回值的函数。 过程还有一种写法,就是将函数的返回值类型定义为Unit。

1 def sayHello(name: String) = "Hello, " + name
2 def sayHello(name: String) { print("Hello, " + name); "Hello, " + name }
3 def sayHello(name: String): Unit = "Hello, " + name

lazy值

在Scala中,提供了lazy值的特性,也就是说,如果将一个变量声明为lazy,则只有在第一次使用该变量时,变量对应的表达式才会发生计算。这种特性对于特别耗时的计算操作特别有用,比如打开文件进行IO,进行网络IO等。

1 import scala.io.Source._
2 lazy val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString

即使文件不存在,也不会报错,只有第一个使用变量时会报错,证明了表达式计算的lazy特性。

1 val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString
2 lazy val lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString
3 def lines = fromFile("C://Users//Administrator//Desktop//test.txt").mkString

 

异常

 1 在Scala中,异常处理和捕获机制与Java是非常相似的。
 2 
 3 try {
 4   throw new IllegalArgumentException("x should not be negative")
 5 } catch {
 6   case _: IllegalArgumentException => println("Illegal Argument!")
 7 } finally {
 8   print("release resources!")
 9 }
10 
11 try {
12   throw new IOException("user defined exception")
13 } catch {
14   case e1: IllegalArgumentException => println("illegal argument")
15   case e2: IOException => println("io exception")
16 }

 

posted @ 2017-04-14 00:32  java一生  阅读(886)  评论(0编辑  收藏  举报