首页 > 代码库 > Scala:Next Steps in Scala

Scala:Next Steps in Scala

Array

 1 val greetStrings = new Array[String](3) 2 greetStrings(0) = "Hello" 3 greetStrings(1) = "," 4 greetStrings(2) = "world!\n" 5  6 for(i <- 0 to 2) 7   print(greetStrings(i)) 8  9 val numNames = Array("zero", "one", "two")10 for(x <- numNames)11   println(x)

针对上面的代码可以说如下几点:

泛型支持

1 new SomeClass[Type Argument](...)

当方法只有一个参数时,可以采用中缀的形式调用。

1 0 to 2 // (0).to(2)

一切皆为对象,所有的运算符都对应对象上的方法。

obj(...) 对应 obj.apply(...)

obj(...) = ... 对应 obj.update(...)

 1 object TestClass { 2   def apply(): TestClass = new TestClass() 3 } 4 class TestClass { 5   def say(msg: String):Unit = { 6     println(msg) 7   } 8  9   def apply(x: Int): Unit = {10     println(x)11   }12 13   def apply(x: Int, y: Int): Unit = {14     println(x)15     println(y)16   }17 18   def apply(args: Int*): Unit = {19     for(x <- args)20       println(x) 21   }22 23   def update(x: Int, msg: String): Unit = {24     println(x)25     println(msg)26   }27 28   def update(x: Int, y: Int, msg: String): Unit = {29     println(x)30     println(y)31     println(msg)32   }33 }34 35 var test = new TestClass()36 test say "hello, world!"37 test(1)38 test(2, 3)39 test(2, 3, 4)40 41 test(1) = "hello"42 test(2, 3) = "world"43 44 println(TestClass())

List

 1 var list = List(3, 4, 5) 2 list = 1 :: 2 :: list 3 list.foreach(println) 4  5 class TestClass { 6   def |: (x: Int): TestClass = { 7     println(x) 8     this 9   }10 }11 12 var test = new TestClass()13 2 |: 1 |: test

List的用法还是比较自然的,从上面的代码可以学到一点额外的知识,即:以“:”号结尾的方法,在采用中缀调用法时,对象在右侧。

Tuple

1 val pair = (99, "Luftballons")2 println(pair._1)3 println(pair._2)

Tuple在语法层面上显出了其特殊性,估计Scala在很多地方对其都有特殊处理,拭目以待了。

 

Scala:Next Steps in Scala