2013-11-21 76 views
3

假設以下類型和方法的存在:斯卡拉:F-界多態性愁楚

trait X[A <: X[A]] 

case class C extends X[C] 

def m(x: PartialFunction[X[_], Boolean]) 

我希望能夠創造一個PartialFunction傳遞到m

第一次嘗試是寫

val f: PartialFunction[X[_], Boolean] = { 
    case c: C => true 
} 

m(f) 

這種失敗type arguments [_$1] do not conform to trait X's type parameter bounds [A <: X[A]]。所以,看來我們必須限制X的類型參數。

第二次嘗試:

val f: PartialFunction[{type A <: X[A]}, Boolean] = { 
    case c: C => true 
} 

m(f) 

這對失敗的m因爲PartialFunction[AnyRef{type A <: X[this.A]},Boolean] <: PartialFunction[X[_],Boolean]是假的應用程序。

是否有任何方式不涉及實際上滿足部分函數的定義和編譯器m應用程序的編譯器?

回答

1

我不知道你想要什麼,但由於您使用的是生存型(在僞裝在_語法),這是你如何使這項工作:

val f: PartialFunction[X[A] forSome {type A <: X[A]}, Boolean] = { 
    case c : C => true 
} 

_語法是不夠好這裏,因爲你需要給生存型右上限。這隻有在更明確的forSome語法纔有可能。

我發現了什麼令人驚訝的,不過,是斯卡拉接受擺在首位的聲明

def m(x: PartialFunction[X[_], Boolean]) 

。它似乎很奇怪,它甚至認爲X[_]一個良構的類型。這是X[A] forSome {type A <: Any}的簡寫,它不應該是X的有效應用程序,因爲它不符合參數邊界。

1

不知道如果這是你想實現什麼,但這是工作順序:

trait X[A <: X[A]] 
case class C extends X[C] 
def m[T<:X[T]](x: PartialFunction[X[T], Boolean]) = print("yahoo!") 

scala> def f[T<:X[T]]:PartialFunction[X[T], Boolean] = { 
    | case c: C => true 
    | } 
f: [T <: X[T]]=> PartialFunction[X[T],Boolean] 

scala> m(f) 
yahoo!