2015-10-19 74 views
1

給定的情況下類:返回<Case Class> .TYPE與案例

scala> case class Foo(x: Int, y: String) 
defined class Foo 

我可以定義返回Either[Foo.type, ...]的方法。

scala> def f: Either[Foo.type, Int] = Left(Foo) 
f: Either[Foo.type,Int] 

當我試圖去構建Foo,我看到了一個編譯時錯誤:

scala> f match { case Left(Foo(a, b)) => a } 
<console>:14: error: constructor cannot be instantiated to expected type; 
found : Foo 
required: Foo.type 
     f match { case Left(Foo(a, b)) => a } 

但以下工作:

scala> f match { case Left(foo) => foo } 
<console>:14: warning: match may not be exhaustive. 
It would fail on the following input: Right(_) 
     f match { case Left(foo) => foo } 
res1: Foo.type = Foo 

給定一個case class,當它適合使用<CASE CLASS>.type類型?

+7

大概幾乎從來沒有? 'Foo.type'是伴侶對象的類型。 –

+3

也許你想要'[Foo,Int]'而不是'[Foo.type,Int]'。 – Jesper

回答

0

那麼,如果你想解構Foo(a,b)那麼你需要存儲一個Foo而不是Foo.type。聲明您有:

def f: Either[Foo.type, Int] = Left(Foo)

基本上是引用同伴對象的時候,而不是你的情況的類的實例。你可能想要類似的東西:

def f: Either[Foo, Int] = Left(Foo(1,"foo"))

+0

對m-z和Jesper的評論感謝,但我寧願發表一個答案,以便可以關閉問題。對於四處尋求幫助的人更有用... –