由于有SML的底子,学习scala的过程也比较顺利。scala很多概念和sml是共通的,在这里记录一下学习中的一点心得。
-
scala是纯OO的语言,语言中所有的元素都是对象。数字是对象,函数也是对象。scala里所有对象的基类是Any,AnyVal是所有值类型对象的父类,包装了JVM中的值对象(int, boolean, float...),AnyRef是所有其他对象的父类,除了能够使用所有Java的类以外,Scala扩展了List、Symbol、Ordered几个比较有用的工具类。
-
scala 代码
-
- scala> 1+2
- unnamed9: Int = 3
-
- scala> var f: int=>int = (1+)
- f: (int) => int = <function></function>
- scala> f(2)
- unnamed10: int = 3
-
scala支持匿名函数。匿名函数其实是从内置的scala模块中派生的。
-
scala 代码
- scala> ( (para:String) => println("hello " + para) ) ("world!")
- hello world!
- unnamed11: Unit = ()
-
-
- scala> var fn = new ( String=>Unit ) { def apply(para:String):Unit = println("he
- llo" + para) }
- fn: AnyRef with (String) => Unit = <function></function>
-
- scala> fn(" world!")
- hello world!
- unnamed23: Unit = ()
- scala的匿名函数可以作为参数或者结果返回
-
scala 代码
-
-
-
- scala> trait o[A, B, C] {
- def apply(f: B=>C, g: A=>B): A=>C = { ( (x:A) => f(g(x))) }
- }
-
- scala> (new o[int,int,int]{}) ( (x=>x/3), (x=>x+1))(2)
- unnamed27: int = 1
- scala支持partial function, currying function以及call by name
-
scala 代码
-
-
- scala> def curry(a:int)(b:int) = a+b
- curry: (int)(int)Int
-
- scala> curry(1)(2)
- unnamed28: Int = 3
-
- scala> var f = curry(1)_
- f: (int) => Int =
-
- scala> f(2)
- unnamed29: Int = 3
-
-
-
- scala> def infloop:int = infloop
- infloop: int
-
- scala> def callbyname(x:int, y: => int) = 1
- callbyname: (int,=> int)Int
-
- scala> callbyname(12, infloop)
- unnamed31: Int = 1
-
- scala> def callbyvalue(x:int, y:int) = 1
- callbyname: (int,=> int)Int
-
-
- scala> callbyvalue(12, infloop)
Scala的特性太多了,以后慢慢记录吧。包括case class, bouned generic, Option class, Implicit type, ADT, type sharing constraint, xml, actor, list等等。