2017-10-05 78 views
0

爲什麼下面的代碼給出了錯誤。我想Function1[-A,+A]Function1不能與協變和逆變參數一起工作

scala> class CSuper 
defined class CSuper 

scala> class CBase extends CSuper 
defined class CBase 

scala> class CSub extends CBase 
defined class CSub 

scala> val f:Function1[CBase,CBase] = (c:CBase) => new CBase 
f: CBase => CBase = $$Lambda$1284/[email protected] 

scala> val f1:Function1[-CBase,+CBase] = (c:CBase) => new CBase 
<console>:1: error: identifier expected but ',' found. 
val f1:Function1[-CBase,+CBase] = (c:CBase) => new CBase 
        ^

scala> 

回答

1

類型使用通用的時候,只有定義它時,您不能指定協方差/逆變。 Function1通用已定義爲 trait Function1[-T1, +R],您不需要指定此項。

+0

好的。所以正確的方法是'scala> val f1:Function1 [CBase,CBase] =(c:CSuper)=> new CSub' –

+0

如果這是你想要的,很可能你不必編寫'Function1',只需要寫'val f1 =(c:CSuper)=> new CSub'。協變/逆變將確保函數適用,即使在某些情況下預期會收到'(CBase)=> CBase'。 – Suma

+0

所以如果我使用'(c:CSuper)=> ...',編譯器將決定協方差或相反性w.r.t. 'CSuper'? –