前言 :
Scala 是一個可直譯、編譯、靜態、運行於 JVM 之上、可與 Java 互操作、融合物件導向編程特性與函式編程風格的程式語言. 特徵抽離共同的介面與實作,類別動態地繼承(extends)或具有(with)特徵.
作為共用實作的特徵 :
特徵不僅可規範抽象、沒有任何實作內容的方法,特徵中還可以撰寫有實作內容的方法。透過適當的設計,你可以將物件之間可能共用的實作抽離至特徵中,在必要時讓類別繼承或具有特徵,使得類別定義時得以精簡.
舉個例子來說,你會定義以下的球類別,並定義了一些比較大小的方法 :
事實上,比較大小順序這件事,許多物件都會用的到,仔細觀察以上的程式碼,你會發現可抽離的共用比較方法,你可以將之重新設計為特徵 :
- trait Ordered {
- def compare(that: Any): Int
- def < (that: Any) = compare(that) < 0
- def <=(that: Any) = (this < that) || (this == that)
- def > (that: Any) = !(this <= that)
- def >=(that: Any) = !(this < that)
- }
事實上,Scala 確實有提供 scala.math.Ordered[A] 特徵來作比大小這種事 :
- package scala
- package math
- import scala.language.implicitConversions
- trait Ordered[A] extends Any with java.lang.Comparable[A] {
- /** Result of comparing `this` with operand `that`.
- *
- * Implement this method to determine how instances of A will be sorted.
- *
- * Returns `x` where:
- *
- * - `x < 0` when `this < that`
- *
- * - `x == 0` when `this == that`
- *
- * - `x > 0` when `this > that`
- *
- */
- def compare(that: A): Int
- /** Returns true if `this` is less than `that`
- */
- def < (that: A): Boolean = (this compare that) < 0
- /** Returns true if `this` is greater than `that`.
- */
- def > (that: A): Boolean = (this compare that) > 0
- /** Returns true if `this` is less than or equal to `that`.
- */
- def <= (that: A): Boolean = (this compare that) <= 0
- /** Returns true if `this` is greater than or equal to `that`.
- */
- def >= (that: A): Boolean = (this compare that) >= 0
- /** Result of comparing `this` with operand `that`.
- */
- def compareTo(that: A): Int = compare(that)
- }
特徵可以定義抽象方法,這可以用來規範物件間必須共同實作的介面,特徵可以定義有具體實作的方法,這可以用來將一些可能會共用的實作或操作獨立出來,在必要時讓類別繼承或具有特徵,讓物件本身在定義時得以精簡.
沒有留言:
張貼留言