注:题目在书上或各PDF版本都有,请自行参考,此答案仅供互相学习和讨论。
1,(条件表达式)
def signum(num : Int) : Int = { if(num > 0) 1 else if(num < 0) -1 else 0 }
2,(表达式)
空{}的值是表达式,类型是Unit。
任何块{}的值都是一个表达式。
3,(赋值)
x为Unit时,x=y=1是合法的。
scala> var x = {}
x: Unit = ()
scala> var y = 10
y: Int = 10
scala> x = y = 1
x: Unit = ()
4,(for)
for(i <- 10.to(0,-1)) println(i)to(end,step)5,(for&函数定义,关键to函数,注意函数定义、返回值,养成良好的习惯,可省略:Unit)def countdown(n : Int) : Unit = { for(i <- n.to(0,-1)) println(i) }6,(for)var sum = 1.toLong for(i <- "Hello") { sum *= i } println(sum)7,(StringOps.foreach())var sum = 1.toLong "Hello".foreach(sum *= _.toLong) println(sum)8,(函数定义)def product(s:String) : Long = { var sum = 1.toLong for(i <- "Hello") { sum *= i } sum }9,(StringOps.take() & StringOps.drop())def rec_product(s : String) : Long = { if(s.length == 1) s.charAt(0).toLong else s.take(1).charAt(0).toLong * rec_product(s.drop(1)) }*take(n),取字符串前n位,从1开始;*drop(n),取删除前n位后的字符串,从1开始;10,(if...else...)def myPow(x : Double , n : Int) : Double = { if(n == 0) 1 else if(n < 0) 1/myPow(x,-n) else if(n > 0 && n%2!=0) x*myPow(x,n - 1) else myPow(x,n/2)*myPow(x,n/2) }