How to use Manifest with Enumeration in Scala?
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 MyEnu开发者_运维百科m, 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.
You did not write what you tried but my guess is that you had your class extend BaseTrait[MyEnum]
. As MyEnum
is an object
the type MyEnum
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.
class Test extends BaseTrait[MyEnum.type] {
protected val enum = MyEnum
protected val valueManifest = manifest[MyEnum.type#Value]
}
精彩评论