Abstract Types && Parameterized Types

Abstract Types && Parameterized Typesgit


Abstract Types(抽象類型) 

Scala的抽象類型成員(Abstract Type Members)沒有和Java等同的。 github

兩個語言中,類,接口(Java),特質(Scala)均可以有方法和字段做爲成員。app

Scala的類(class)或特質(trait)能夠有類型成員,下面例子是抽象類型成員:ide

object app_main extends App {
  // 經過給出這兩個成員的具體定義來對這個類型進行實例化
  val abs = new AbsCell {
    override type T = Int
    override val init: T = 12
    override var me: S = "liyanxin"
  }

  println(abs.getMe)
  println(abs.getInit)

}

trait Cell {
  // 抽象類型成員S
  type S
  var me: S

  def getMe: S = me

  def setMe(x: S): Unit = {
    me = x
  }
}


/**
 * AbsCell 類既沒有類型參數也沒有值參數,
 * 而是定義了一個抽象類型成員 T 和一個抽象值成員 init。
 */
abstract class AbsCell extends Cell {

  //在子類內部具體化抽象類型成員S
  override type S = String
  // 抽象類型成員 T
  type T
  val init: T
  private var value: T = init

  def getInit: T = value

  def setInit(x: T): Unit = {
    value = x
  }
}

運行並輸出:函數

liyanxin
0

參考:http://alanwu.iteye.com/blog/483959spa

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

關於下面二者的區別:code

abstract class Buffer {
  type T
  val element: T
}

rather that generics, for example,orm

abstract class Buffer[T] {
  val element: T
}

請見:http://stackoverflow.com/questions/1154571/scala-abstract-types-vs-genericsblog


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 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

==============END==============

相關文章
相關標籤/搜索