如何在 Scala 中使用清单和枚举?
如果我有以下 Scala 代码:
trait BaseTrait[EnumType <: Enumeration] {
protected val enum: EnumType
protected val valueManifest: Manifest[EnumType#Value]
}
object MyEnum extends Enumeration {
val Tag1, Tag2 = Value
}
并且我想创建一个使用 MyEnum 实现 BaseTrait 的类,我可以这样做:
class BaseClass[EnumType <: Enumeration]
(protected val enum: EnumType)
(implicit protected val valueManifest: Manifest[EnumType#Value])
extends BaseTrait[EnumType] {
}
class Test extends BaseClass(MyEnum)
但是如果没有中间基类,我该如何做到这一点呢?所有其他尝试总是导致编译错误。
If I have the following Scala code:
trait BaseTrait[EnumType <: Enumeration] {
protected val enum: EnumType
protected val valueManifest: Manifest[EnumType#Value]
}
object MyEnum extends Enumeration {
val Tag1, Tag2 = Value
}
And I want to create a class which implements BaseTrait using MyEnum, I can do it like this:
class BaseClass[EnumType <: Enumeration]
(protected val enum: EnumType)
(implicit protected val valueManifest: Manifest[EnumType#Value])
extends BaseTrait[EnumType] {
}
class Test extends BaseClass(MyEnum)
But how can I do it without an intermediary base class? All other attempts always resulted in a compile error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有编写您尝试过的内容,但我猜测您的类扩展了
BaseTrait[MyEnum]
。由于MyEnum
是一个object
,因此MyEnum
类型不存在(除非您还使用该名称定义了一个类或特征)。您必须显式提供单例类型
MyEnum.type
作为类型参数。You did not write what you tried but my guess is that you had your class extend
BaseTrait[MyEnum]
. AsMyEnum
is anobject
the typeMyEnum
does not exist (unless you also define a class or trait with that name).You have to explicitly supply the singleton type
MyEnum.type
as type parameter.