Scala 3 — 書籍

泛型

語言

泛型類別(或特質)將型別作為方括號 [...] 中的參數。Scala 慣例是用單一字母(例如 A)來命名這些型別參數。然後,型別可以在類別中使用,視需要用於方法實例參數或回傳型別

// here we declare the type parameter A
//          v
class Stack[A] {
  private var elements: List[A] = Nil
  //                         ^
  //  Here we refer to the type parameter
  //          v
  def push(x: A): Unit =
    elements = elements.prepended(x)
  def peek: A = elements.head
  def pop(): A = {
    val currentTop = peek
    elements = elements.tail
    currentTop
  }
}
// here we declare the type parameter A
//          v
class Stack[A]:
  private var elements: List[A] = Nil
  //                         ^
  //  Here we refer to the type parameter
  //          v
  def push(x: A): Unit =
    elements = elements.prepended(x)
  def peek: A = elements.head
  def pop(): A =
    val currentTop = peek
    elements = elements.tail
    currentTop

這個 Stack 類別的實作會將任何類型作為參數。泛型的優點是,現在你可以建立 Stack[Int]Stack[String] 等,讓你能夠重複使用 Stack 的實作,以用於任意元素類型。

以下是如何建立和使用 Stack[Int]

val stack = new Stack[Int]
stack.push(1)
stack.push(2)
println(stack.pop())  // prints 2
println(stack.pop())  // prints 1
val stack = Stack[Int]
stack.push(1)
stack.push(2)
println(stack.pop())  // prints 2
println(stack.pop())  // prints 1

請參閱 變異區段,以了解如何使用泛型類型表達變異。

此頁面的貢獻者