在scala中惟有3个表达式不返回值java
一个是while和do-while.while在scala叫循环,而不是表达式.是由于它们不能生产有意义的结果.c++
还有一个是finally,若是finally产生结果那根据finally的特性它在函数最后必定会执行那么try和catch中的结果将毫无心义.永远只会返回finally中的结果.如def returnTest = try{1}finally{2},那么returnTest永远只能是2.全部这和java是不同的.scala中finally不会返回任何内容只用做资源释放.ide
在scala中任何赋值语句都不会返回被赋值变量的值.只会返回一个"()".函数
var line = "" while((line = readLine()) != ""){ println("Read : " + line) }
这个在java,c,c++中惯用的读取文本行,在scala中不行.由于line = readLine() 永远只返回 "()", () != "" 是永远不相等的.scala
scala> val f = (_:Int) + (_:Int) f: (Int,Int) => Int = <function> scala> f(5,10) res11: Int = 15
请注意_ + _ 将扩展成带两个参数的函数字面量.这样也解释了为什么仅当每一个参数在函数字面量中最多出现一次时,你才能使用这种短格式.多个下划线指代多个参数,而不是单个参数的重复使用.第一个下划线表明第一个参数,第二个下划线表明第二个,第三个,........,以此类推.code
定义无参方法:若是你调用的函数执行了操做就使用括号,但若是仅提供了对某个属性的访问,那么省略括号.对象
扩展类:若是你省略extends子句,Scala编译器将隐式地扩展scala.AnyRef,与java默认继承java.lang.Object继承
java中抽象方法必须指定abstract而scala中不须要指定abstract.接口
java有4个命名空间(分别是字段,方法,类型和包),scala仅有2个命名空间:值(包含字段,方法,包还有单例对象),类型(包括类和特质名)资源
scala的Any是任何类的基类
特质与类出了3点以外.其余都与类同样.
要点以下:
特质:次序性,粗略的说,越靠近右侧的特质越先起做用.当你调用带混入的类的方法时,最右侧特质的方法首先被调用.若是那个方法调用了super,它调用其左侧特质的方法,以此类推.
import scala.collection.mutable.ArrayBuffer abstract class IntQueue { def get(): Int def put(x: Int) } trait Incrementing extends IntQueue { abstract override def put(x: Int) = super.put(x + 1) } trait Filtering extends IntQueue { abstract override def put(x: Int) = if (x >= 0) super.put(x) } class BasicIntQueue extends IntQueue { private val buf = new ArrayBuffer[Int]() override def get(): Int = buf.remove(0) override def put(x: Int) { buf += x } } object BasicIntQueue { def main(args: Array[String]): Unit = { val queue = new BasicIntQueue with Filtering with Incrementing queue.put(10) queue.put(-1) println(queue.get()) println(queue.get()) } }