2009-02-23 26 views
7

我只是想知道,我可以將元組類型分解爲它在Scala中的組件類型嗎?解開Scala中的元組類型

我的意思是,像這樣

trait Container { 
    type Element 
} 

trait AssociativeContainer extends Container { 
    type Element <: (Unit, Unit) 
    def get(x : Element#First) : Element#Second 
} 

回答

3

無法解壓縮本身,但也許,這達到你想要什麼:

type First 
    type Second 
    type Element = (First, Second) 
    def get(x: First): Second 
+0

這就是我認爲我需要做的,但是想避免,因爲這會改變擴展這個特性的類的實現。 – jpalecek 2009-02-23 00:47:03

0

我有點晚了這一點,但是使用模式匹配呢?還沒有比較正確的返回類型,我的語法可能有點過,但這裏有雲:

def get[K](key: K): Iterable[Any] { 
    for ((key, x) <- elements) yield x 
} 
3

這不解開的類型,但它確實限制AB調用get當類型。

trait Container { 
    type Element 
} 

trait AssociativeContainer extends Container { 
    type Element <: Tuple2[_, _] 

    def get[A, B](x: A)(implicit ev: (A, B) =:= Element): B 
} 

這看起來很有希望,但欺騙 - 如果Element是抽象的這是行不通的。

def Unpack[T<:Tuple2[_, _]] = new { 
    def apply[A, B](implicit ev: T <:< (A, B)) = new { 
    type AA = A 
    type BB = B 
    } 
} 

trait AssociativeContainer { 
    type Element = (Int, String) 
    val unpacked = Unpack[Element].apply 
    type A = unpacked.AA 
    type B = unpacked.BB 

    1: A 
    "": B 
    def get(x: A): B 
}