2015-10-19 80 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的评论感谢,但我宁愿发表一个答案,以便可以关闭问题。对于四处寻求帮助的人更有用... –