在 Either 中指定案例对象的类型

Specifying type of a Case Object in Either

如果我有一个对象如下:

case object Foo

我尝试创造这样的价值

Either[Foo, B]

我收到一个编译错误,提示无法找到 Foo。但如果我这样做:

Either[Foo.type, B]

编译通过。我的问题是这样做是否正确?

无论何时你想在 Scala 中声明 object 的类型,你都必须像 YourObject.type 那样声明它。

原因很简单,因为YourObject已经是实例。所以 .type 是你必须在 Scala.

中声明对象类型 (Singleton) 的方式

举个例子:

object YourObject

def doit(obj: YourObject.type) = {}

def doitEventually(obj: Option[YourObject.type]) = {}


doit(YourObject)
doitEventually(Some(YourObject))

我找不到相应的文档,也许有人可以帮忙。

规范在这里:singleton-types(Mojo 在评论中提到)