抽象類定義:abstract class Element{ def contents:Array[String]; def height = contents.length}
java
定義無參數方法:若是僅提供對象的某個數據的訪問(沒有反作用的方法),那麼久省略括號。定義成無參數方法。app
若是無參數方法用用到的地方較多而且比較頻繁,建議把無參數方法def height = contents.length變成val height = 函數
contents.length的字段值。二者的區別是:由於字段值在類初始化的時候被預編譯,而方法調用在每次調用的時候都須要計算,ui
另外一方面,使用字段須要爲每一個Element對象分配更多空間。因此用無參數方法仍是字段值看狀況而定。
spa
在scala中字段和方法屬於相同的命名空間。這讓字段能夠重寫無參數方法。scala
class WontCompile{ private var f = 0; def f = 1;}//編譯無妨經過,由於字段和方法重名了。
code
java爲定義準備了4個命名空間(分別是字段,方法,類,包),scala僅有2個命名空間(值(字段,方法,包,單例對象),類型(類和特質名))orm
在Scala中有一個關鍵字是implicit
對象
咱們先來看一個例子:ci
def display(input:String):Unit = println(input)
咱們能夠看到,display
函數的定義只是接受String
類型的入參,所以調用display("any string")
這樣的函數是沒問題的。可是若是調用display(1)
這樣的入參不是String類型的話,編譯會出錯的。
若是咱們想讓display函數也可以支持Int類型的入參的話,除了咱們從新定一個def display(input:Int):Unit = println(input)
這樣的函數之外,咱們還能夠在相同的做用域內用implicit
關鍵字定義一個隱式轉換函數,示例代碼以下:
object ImplicitDemo { def display(input:String):Unit = println(input) implicit def typeConvertor(input:Int):String = input.toString implicit def typeConvertor(input:Boolean):String = if(input) "true" else "false"// implicit def booleanTypeConvertor(input:Boolean):String = if(input) "true" else "false" def main(args: Array[String]): Unit = { display("1212") display(12) display(true) } }
咱們定義了2個隱式轉換函數:
implicit def typeConvertor(input:Int):String = input.toString implicit def typeConvertor(input:Boolean):String = if(input) "true" else "false"
這樣display
函數就能夠接受String、Int、Boolean類型的入參了。注意到上面咱們的例子中註釋的那一行,若是去掉註釋的那一行的話,會在運行的時候出現二義性:
Error:(18, 13) type mismatch; found : Boolean(true) required: StringNote that implicit conversions are not applicable because they are ambiguous: both method typeConvertor in object ImplicitDemo of type (input: Boolean)String and method booleanTypeConvertor in object ImplicitDemo of type (input: Boolean)String are possible conversion functions from Boolean(true) to String display(true) ^
得出的結論是:
記住隱式轉換函數的同一個scop中不能存在參數和返回值徹底相同的2個implicit函數。
隱式轉換函數只在乎 輸入類型,返回類型。
隱式轉換是scala的語法靈活和簡潔的重要組成部分