Scala学习笔记(二)—chapter2

时间:2022-12-25 10:56:43

1、scala中的Unit相当于java或C里的void。

2、块,在scala中,{ }块包含一系列表达式。块中最后一个表达式的值就是块的值。

3、循环语句
(1)for循环和while\do while
Scala学习笔记(二)—chapter2

i <- 1 to 5: 1,2,3, 4, 5  
i <- 1 until 5: 1, 2, 3, 4

<-表示遍历右边区间每个元素赋值给左边。

(2) 可以以变量 <- 表达式 的形式提供多个生成器,用分号将它们隔开。每个生成器都可以待一个守卫,以if开头的boolean表达式。

for (i <- 1 to 3; j <- 1 to 3) print((10 * i + j) + " ")
11 12 13 21 22 23 31 32 33 res0: Unit = ()
//守卫的if之前并没有分号
for (i <- 1 to 3 if i != 2; j <- 1 to 3 if i != j) print((10 * i + j) + " ")
12 13 31 32 res0: Unit = ()

(3) 如果for循环的循环体以yield开始,则该循环会构造出一个集合,每次迭代生成集合中得一个值。这类循环叫做for推导式。

for (i <- 0 to 5) yield i

4、函数。
(1)定义函数需要给出函数的名称、参数和函数体:
//scala编译器可以根据=右边的表达式的类型推断出返回值的类型。

def abs(x : Double) = if (x > 0) x else -x

(2)在调用函数时可以不显示的给出所有参数值,可以是用默认参数。

def decorate(str:String, left:String="[", right:String="]") = left + str + right
decorate: decorate[](val str: String,val left: String = "[",val right: String = "]") => String
decorate("hello")
res0: String = [hello]

(3)变长参数

scala> :paste
// Entering paste mode (ctrl-D to finish)

def count(args : Int*) = {
var result = 0
for (arg <- args) {
result += arg
}
result
}
val s = count(1, 2)
// Exiting paste mode, now interpreting.

count: (args: Int*)Int
s: Int = 3

(4)过程:如果函数体包含在花括号当中但没有前面的=号,那么返回类型就是Unit。这样的函数被称做过程(procedure)

5、懒值:当val被声明为lazy时,它的初始化将被推迟,直到首次使用时。可以把懒值当做是介于val和def的中间状态。

lazy val words = Source.fromFile("/").mkString

6、try/catch、try/finally、try/catch/finally语句。try/catch/finally语句块都是使用{ },catch语句块中使用模式匹配异常。

import java.io.FileNotFoundException
import scala.io.Source
try {
val words = Source.fromFile("/").mkString
} catch {
case ex:FileNotFoundException => println("exec catch")
} finally {
println("exec finally")
}

例题:
Scala学习笔记(二)—chapter2

def getResult(arg : Int) : Int = {
if (arg > 0)
1
else if (arg < 0)
-1
else
0
}
getResult(-2)
res0: Int = -1

Scala学习笔记(二)—chapter2

//返回Unit
def getResult() = {}
getResult()

Scala学习笔记(二)—chapter2

var y = 4
var x = ()
x = y = 7

Scala学习笔记(二)—chapter2

for (i <- 0 to 10 reverse) println(i)

Scala学习笔记(二)—chapter2

def countdown(n : Int): Unit = {
if (n < 0)
return
for (i <- 0 to n reverse)
println(i + " ")
}
countdown(5)
5
4
3
2
1
0
res0: Unit = ()

Scala学习笔记(二)—chapter2

var result:Long = 1
for (i <- "Hello") {
result = result * i.toLong
}
result

Scala学习笔记(二)—chapter2

var result:Long = 1
"Hello".foreach(result *= _.toLong)
result

Scala学习笔记(二)—chapter2

scala> :paste
// Entering paste mode (ctrl-D to finish)
def product(s : String) : Long = {
var result:Long = 1
for (i <- s) {
result = result * i.toLong
}
result
}
product("Hello")
// Exiting paste mode, now interpreting.
product: (s: String)Long
res8: Long = 9415087488

Scala学习笔记(二)—chapter2

//注意"Hello".take(1)返回的是一个String类型
def product(s:String):Long = {
if (s.length == 1)
s.charAt(0).toLong
else
s.take(1).charAt(0).toLong * product(s.drop(1))
}
product("Hello")
res0: Long = 9415087488