@Arslan6and6
2016-08-29T02:35:55.000000Z
字数 2119
阅读 751
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
默认函数
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 =
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序列
函数体前没有= ,表示返回函数值为空 Util ,调用函数使用的是副作用 ,也叫过程
def box (s:String){var border = "-"*s.length + "--\n"println(border + "|" + s +"|\n" + border)}box: (s: String)Unitscala> box("mini")------|mini|------
定义时会延迟初始化,也就是定义错了也不会立即报错,而是调用时才报错。
懒值可以优化开销较大的初始化
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)
scala> import scala.math._import scala.math._scala> def d(x:Int):Double ={| if(x>=0){sqrt(x)}| else throw new IllegalArgumentException("x must >= 0")| }d: (x: Int)Doublescala> d(2)res16: Double = 1.4142135623730951scala> d(0)res17: Double = 0.0scala> d(-6)java.lang.IllegalArgumentException: x must >= 0
第二章练习
scala> def s(x:Int) {| if (x>0) print(1)| else if (x<0) print(-1)| else print(0)| }s: (x: Int)Unitscala> s(1)1scala> s(-10)-1scala> s(0)0scala> for(x <- 1 to 10 reverse) print(x)warning: there were 1 feature warning(s); re-run with -feature for details10987654321scala> for (x <-1 to 10 ; y = 10-x) print(y)9876543210scala> for (x <-1 to 10 ; y = 11-x) print(y)10987654321scala> def re(x:Int) {for(i <- 0 to x reverse) print(i)}warning: there were 1 feature warning(s); re-run with -feature for detailsre: (x: Int)Unitscala> re(6)6543210