Scala Parameterized Types_參數化型別_泛型

來源:互聯網
上載者:User

標籤:

Scala Parameterized Types_參數化型別_泛型


Scala supports parameterized types, which are very similar to generics in Java. (We could use the two terms interchangeably(可交換的), 

but it’s more common to use “parameterized types” in the Scala community and “generics” in the Java community.) The most obvious difference is in the

syntax, where ????????Scala uses square brackets ([...] ), while Java uses angle brackets (<...>).????????


用型別參數化類

For example, a list of strings would be declared as follows:

class GenCell[T](init: T) {  private var value: T = init  def get: T = value  //Unit相當於返回void  def set(x: T): Unit = {    value = x  }}

在上面的定義中,“T”是一個型別參數,可被用在GenCell類和它的子類中。類參數可以是任意(arbitrary)的名字。用[]來包圍,而不是用()來包圍,用以和值參數進行區別。


用型別參數化函數

如下程式碼範例

class GenCell[T](init: T) {  private var value: T = init  def get: T = value  //Unit相當於返回void  def set(x: T): Unit = {    value = x  }}object app_main_7 extends App {  //用T參數化函數  def swap[T](x: GenCell[T], y: GenCell[T]): Unit = {    val t = x.get;    x.set(y.get);    y.set(t)  }  val x: GenCell[Int] = new GenCell[Int](1)  val y: GenCell[Int] = new GenCell[Int](2)  swap[Int](x, y)  println(x.get)  println(y.get)}

參考:https://github.com/wecite/papers/blob/master/An-Overview-of-the-Scala-Programming-Language/5.Abstraction.md


Scala Parameterized Types_參數化型別_泛型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.