给出一个案例类:
library(purrr)
mylist %>% zip_n(.simplify = TRUE)
#$a
# list_1 list_21 list_22 list_31 list_32 list_33 list_34 list_41
# 2 5 6 10 5 8 1 2
#list_42 list_43
# 5 58
#
#$b
# list_1 list_21 list_22 list_31 list_32 list_33 list_34 list_41
# 3 2 3 9 6 2 9 69
#list_42 list_43
# 6 23
我可以定义一个返回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
类型?
答案 0 :(得分:0)
好吧,如果您要解构Foo(a,b)
,那么您需要存储Foo
而不是Foo.type
。您的声明:
def f: Either[Foo.type, Int] = Left(Foo)
基本上每次引用伴随对象,而不是您的案例类的实例。你可能想要这样的东西:
def f: Either[Foo, Int] = Left(Foo(1,"foo"))