这里有 3 种使用 Algebraic Data Types (ADT) 的可能性。
首先是object-oriented 方式:
sealed trait LinkedListNode[A] {
def calleachnode(inputfunction : A => Unit): Unit
}
case class BranchNode[A](value:A, next: LinkedListNode[A]) extends LinkedListNode[A] {
def calleachnode(inputfunction : A => Unit): Unit = {
inputfunction(value)
next.calleachnode(inputfunction)
}
}
case class LeafNode[A](value:A) extends LinkedListNode[A] {
def calleachnode(inputfunction : A => Unit): Unit = {
inputfunction(value)
}
}
或者,如果您愿意,也可以使用模式匹配:
sealed trait LinkedListNode[A] {
def calleachnode(inputfunction : A => Unit): Unit = this match {
case BranchNode(value, next) =>
inputfunction(value)
next.calleachnode(inputfunction)
case LeafNode(value) =>
inputfunction(value)
}
}
case class BranchNode[A](value:A, next: LinkedListNode[A]) extends LinkedListNode[A]
case class LeafNode[A](value:A) extends LinkedListNode[A]
您可以使用以下方法测试这些解决方案:
val lln = BranchNode(12, LeafNode(2))
lln.calleachnode((i) => println(i * 2))
现在有更多functional 使用ADT 的方式:
sealed trait LinkedListNode[A]
case class BranchNode[A](value:A, next: LinkedListNode[A]) extends LinkedListNode[A]
case class LeafNode[A](value:A) extends LinkedListNode[A]
def calleachnode[A](listNode: LinkedListNode[A], inputfunction : A => Unit): Unit = listNode match {
case BranchNode(value, next) =>
inputfunction(value)
calleachnode(next, inputfunction)
case LeafNode(value) =>
inputfunction(value)
}
测试看起来有点不同:
val lln = BranchNode(12, LeafNode(2))
calleachnode[Int](lln, (i) => println(i * 2))