Scala编程入门---函数过程,Lazy值和异常

过程:

在Scala中,定义函数时,如果函数体直接包裹在花括号里面,而没有使用=连接,则函数的返回值类型就是Unit.这样的函数就被称之为过程。

过程通常用于不需要返回值类型的函数。

过程还有一种写法,就是将函数的放回值类型定义为Unit.

def sayHello(name:String) = "Hello,"+name #返回类型是String
def sayHello(name:String) {print("Hello,"+name);"Hello,"+name} #没有返回值 也就是返回值类型为Unit
def sayHello(name:String) :Unit ="Hello,"+name #返回值类型为Unit

lazy 值:

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

import.scala.io.Source._
lazy val lines = fromFile("c:......test.txt").mkString #即使文件不存在,也不会报错,只有在第一次使用变量的时候才会报错,证明表达式计算的lazy特性。

val lines = fromFile("c:.......test.txt").mkString    
lazy val lines = fromFile("c:.......test.txt").mkString   
def lines = fromFile("c:.......test.txt").mkString   

异常:

在Scala中,异常处理和捕获机制与JAVA是非常相似的。

但是在catch块中 有一个匹配的机制。

try{

  throw new lllegalArgumentException("xx should  not  be negative")

}catch{

  case e1:lllegalArgumentException =>pirnt("lllegal argument")
   case e2:IOException => print("io exception")
}
原文地址:https://www.cnblogs.com/yeszero/p/6945290.html