class C[T, U] { }
// <=>
class C {
type C$T
type C$U
}
Dotty desugar多态方法如下例所示?
def m[T, U](x: T, u: U): T = x
// <=>
?
答案 0 :(得分:5)
与多态类不同,多态方法不会被贬低。它们从根本上保持多态性。
答案 1 :(得分:2)
您可能需要从最近的DOT论文The Essence of DOT by Nada Amin, Samuel Grütter, Martin Odersky, Tiark Rompf, and Sandro Stucki的第13页第5.2节的底部开始。它显示了Scala中简单协变多态List[+A]
类型的实现。特别值得注意的是多态cons[A]
方法:
package scala.collection.immutable
trait List[+A] {
def isEmpty: Boolean
def head: A
def tail: List[A]
}
object List {
def cons[A](hd: A, tl: List[A]) = new List[A] {
def isEmpty = false
def head = hd
def tail = tl
}
}
它是如何在DOT中编码的:
let scala_collection_immutable = ν(sci) {
List = μ(self: {A; isEmpty: bool.Boolean; head: self.A; tail: sci.List∧{A <: self.A}})
cons: ∀(x: {A})∀(hd: x.A)∀(tl: sci.List∧{A <: x.A})sci.List∧{A <: x.A} =
λ(x: {A})λ(hd: x.A)λ(tl: sci.List∧{A <: x.A})
let result = ν(self) {
A = x.A; isEmpty = bool.false; head = hd; tail = tl }
in result
}: { μ(sci: {
List <: μ(self: {A; head: self.A; tail: sci.List∧{A <: self.A}})
cons: ∀(x: {A})∀(hd: x.A)∀(tl: sci.List∧{A <: x.A})sci.List∧{A <: x.A}
})}
in …
反过来,它应该让你直截了当地知道它是如何在Dotty中编码的。
然后,第15页将向您展示如何将desugared DOT映射回Scala:object scala_collection_immutable { sci =>
trait List { self =>
type A
def isEmpty: Boolean
def head: self.A
def tail: List{type A <: self.A}
}
def cons(x: {type A})(hd: x.A)(tl: sci.List{type A <: x.A})
: sci.List{type A <: x.A} = new List{ self =>
type A = x.A
def isEmpty = false
def head = hd
def tail = tl
}
}
如您所见,多态方法的编码与多态特征大致相同:type参数成为抽象类型成员,在本例中是细化类型的抽象类型成员(也称为结构类型) :
x : A
// becomes
x : {type A}