1
我最近一直在經歷的書「斯卡拉通過示例」中,筆者創建了一個抽象類來表示一組整數的「INTSET」兩個子類(EmptySet和NonEmptySet)如下:什麼時候應該使用單獨的類來表示空容器?
abstract class Stack[A] {
def push(x: A): Stack[A] = new NonEmptyStack[A](x, this)
def isEmpty: Boolean
def top: A
def pop: Stack[A]
}
class EmptyStack[A] extends Stack[A] {
def isEmpty = true
def top = error("EmptyStack.top")
def pop = error("EmptyStack.pop")
}
class NonEmptyStack[A](elem: A, rest: Stack[A]) extends Stack[A] {
def isEmpty = false
def top = elem
def pop = rest
}
我的問題是這樣的:這個將空容器表示爲自己的類而不是創建一個具體類來處理空和非空的情況的範例有多大用處?