Scala 返回<;案例类别>;。带Case类的类型

Scala 返回<;案例类别>;。带Case类的类型,scala,Scala,给定一个案例类: scala> case class Foo(x: Int, y: String) defined class Foo 我可以定义一个返回的方法[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 } &l

给定一个案例类:

scala> case class Foo(x: Int, y: String)
defined class Foo
我可以定义一个返回
的方法[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(a,b))=>a}
:14:错误:无法将构造函数实例化为预期类型;
发现:富
必需: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
scala>f match{case Left(foo)=>foo}
:14:警告:匹配可能不完整。
它将在以下输入上失败:正确(u3;)
f match{case Left(foo)=>foo}
res1:Foo.type=Foo

给定一个
案例类
,什么时候使用
类型
类型合适?

好吧,如果你想解构
Foo(a,b)
,那么你需要存储一个
Foo
,而不是
Foo.type
。你的声明:

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

基本上每次都引用伴随对象,而不是case类的实例。您可能需要以下内容:


def:note[Foo,Int]=Left(Foo(1,“Foo”)
如果你想解构
Foo(a,b)
那么你需要存储a
Foo
而不是
Foo.type
。你的声明:

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

基本上每次都引用伴随对象,而不是case类的实例。您可能需要以下内容:


def:not[Foo,Int]=Left(Foo(1,“Foo”))

可能永远不会
Foo.type
是伴生对象的类型。可能您想要
或者[Foo,Int]
而不是
或者[Foo.type,Int]
。可能永远不会
Foo.type
是伴生对象的类型。可能您希望
或者[Foo,Int]
而不是
或者[Foo.type,Int]
。感谢m-z和Jesper的评论,但我宁愿发布一个答案,这样问题就可以结束了。对于四处寻找帮助的人来说更有用…感谢m-z和Jesper的评论,但我宁愿发布一个答案,这样问题就可以结束了。对四处寻找帮助的人更有用。。。