[关闭]
@Arslan6and6 2016-08-29T02:35:55.000000Z 字数 2119 阅读 681

scala学习 第二章 控制结构和函数

scala学习


每个生成器可以带一个守卫,以if开头的Boolean
scala> for(x <- 1 to 3 if x !=2) print("x:"+x+"\n")
x:1
x:3
scala> for(x <- 1 to 3; y <- 1 to 5) print("x:"+x+" "+"y:"+y+"\n")
x:1 y:1
x:1 y:2
x:1 y:3
x:1 y:4
x:1 y:5
x:2 y:1
x:2 y:2
x:2 y:3
x:2 y:4
x:2 y:5
x:3 y:1
x:3 y:2
x:3 y:3
x:3 y:4
x:3 y:5

scala> for(x <- 1 to 3; y <- 1 to 5 if x != y) print("x:"+x+" "+"y:"+y+"\n")
x:1 y:2
x:1 y:3
x:1 y:4
x:1 y:5
x:2 y:1
x:2 y:3
x:2 y:4
x:2 y:5
x:3 y:1
x:3 y:2
x:3 y:4
x:3 y:5

scala> for(x <- 1 to 3; y <- 1 to 5 if x == y) print("x:"+x+" "+"y:"+y+"\n")
x:1 y:1
x:2 y:2
x:3 y:3

可以在循环中使用变量
scala> for(x <- 1 to 3 ; z = x*10 ; y <- z to z+3) println("x:"+x+"\t"+"y:"+y)
x:1 y:10
x:1 y:11
x:1 y:12
x:1 y:13
x:2 y:20
x:2 y:21
x:2 y:22
x:2 y:23
x:3 y:30
x:3 y:31
x:3 y:32
x:3 y:33

2.8默认参数和带名参数

默认函数
scala> def decorate(str:String, left:String="<", right:String=">")= left + str + right
decorate: (str: String, left: String, right: String)String

scala> decorate("king")
res1: String =

2.9变长参数

scala> def sum (args:Int*)= {
var res = 0
for (x <- args) res+= x
res
}
sum: (args: Int*)Int
scala> sum(3)
res53: Int = 3
scala> sum(3,4)
res54: Int = 7
scala> sum(3,4,3)
res55: Int = 10
scala> sum(1 to 5:_)
res57: Int = 15
_
作为1to5的seq序列

2.10过程

函数体前没有= ,表示返回函数值为空 Util ,调用函数使用的是副作用 ,也叫过程

  1. def box (s:String){
  2. var border = "-"*s.length + "--\n"
  3. println(border + "|" + s +"|\n" + border)
  4. }
  5. box: (s: String)Unit
  6. scala> box("mini")
  7. ------
  8. |mini|
  9. ------

2.11懒值

定义时会延迟初始化,也就是定义错了也不会立即报错,而是调用时才报错。
懒值可以优化开销较大的初始化

scala> lazy val words = scala.io.Source.fromFile("/tmp/word").mkString
words: String =

scala> print(words)
java.io.FileNotFoundException: /tmp/word (No such file or directory)

2.12异常

  1. scala> import scala.math._
  2. import scala.math._
  3. scala> def d(x:Int):Double ={
  4. | if(x>=0){sqrt(x)}
  5. | else throw new IllegalArgumentException("x must >= 0")
  6. | }
  7. d: (x: Int)Double
  8. scala> d(2)
  9. res16: Double = 1.4142135623730951
  10. scala> d(0)
  11. res17: Double = 0.0
  12. scala> d(-6)
  13. java.lang.IllegalArgumentException: x must >= 0

第二章练习

  1. scala> def s(x:Int) {
  2. | if (x>0) print(1)
  3. | else if (x<0) print(-1)
  4. | else print(0)
  5. | }
  6. s: (x: Int)Unit
  7. scala> s(1)
  8. 1
  9. scala> s(-10)
  10. -1
  11. scala> s(0)
  12. 0
  13. scala> for(x <- 1 to 10 reverse) print(x)
  14. warning: there were 1 feature warning(s); re-run with -feature for details
  15. 10987654321
  16. scala> for (x <-1 to 10 ; y = 10-x) print(y)
  17. 9876543210
  18. scala> for (x <-1 to 10 ; y = 11-x) print(y)
  19. 10987654321
  20. scala> def re(x:Int) {for(i <- 0 to x reverse) print(i)}
  21. warning: there were 1 feature warning(s); re-run with -feature for details
  22. re: (x: Int)Unit
  23. scala> re(6)
  24. 6543210
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注