笔记内容比较杂!
var hw =new helloworld("Hi,my name is lming_08")
var表示变量,val表示常量
var hw:helloworld =new helloworld("Hi,my name is lming_08")
scala> def max(x: Int, y: Int): Int = if (x < y) y else x max: (Int,Int)Int
// 函数内部定义函数 def squreInc(x : Int) = { def squre(a : Int) = a * a squre(x) + 1 }或者定义匿名函数
// 函数内部定义匿名函数 def squreInc2(x : Int) = { val squre = (a : Int) => a * a squre(x) + 1 }
>>> func = lambda x : x + 1 >>> func(1) 2
scala> def func = 1+2 func: Int scala> func res0: Int = 3
def arrLoop(arr:Array[String])={ arr(0)="abc" arr(1)="123" arr(2)="ABC" for(elem<- arr) println(elem+", hello") } def arrLoop2(arr:Array[String])={ arr(0)="+abc" arr(1)="+123" arr(2)="+ABC" arr.foreach(elem => println(elem)) } def arrLoop3(arr:Array[String])={ arr(0)="-abc" arr(1)="-123" arr(2)="-ABC" for(i <- 0 to arr.length -1){ println(arr(i)) } }针对第三种下标for循环,除了to还有until, 表示[0, arr.length-2]
/**************************************************************
* 时隔一年之后再次踏上学习Scala之路 2015.08.30 22:33
**************************************************************/
8. Scala中能不用var变量就不用!
原因是Scala是为并发编程而生,为函数式编程而生,所以对于Scala程序员最好使用val变量。
一些取代var变量的例子:
1)原代码
var filename = "default.txt" if (!args.isEmpty) filename = args(0)取代后的代码
val filename = if (!args.isEmpty) args(0) else "default.txt"
2)
9.while 和do while被称作循环,而不是表达式
scala> def greet() { println("hi") } greet: ()Unit scala> greet() == () hi res0: Boolean = true
def greet() : Unit = { println("hi") } def greet() = { println("hi") }
var line = "" while ((line = readLine()) != "") // This doesn't work! println("Read: "+ line)
10.集合操作
http://www.artima.com/pins1ed/collections.html
scala> val jetSet = Set("Boeing", "Airbus") jetSet: scala.collection.immutable.Set[String] = Set(Boeing, Airbus) scala> jetSet += "Lear" <console>:12: error: value += is not a member of scala.collection.immutable.Set[String] jetSet += "Lear"
这是因为换成var后, += 会生成一个新的Set, 等价于
var y = jetSet y += "Lear"
http://stackoverflow.com/questions/5074179/val-or-var-mutable-or-immutable
未完待续。。。
参考资料:http://www.artima.com/scalazine/articles/steps.html
github练习代码