我只是想知道是否有可能遍历Scala中的一个密封的特质? 如果不是,为什么不可能? 由于特征是密封的,应该可以不?
我想要做的就是这样的事情:
sealed trait ResizedImageKey {
/**
* Get the dimensions to use on the resized image associated with this key
*/
def getDimension(originalDimension: Dimension): Dimension
}
case class Dimension(width: Int, height: Int)
case object Large extends ResizedImageKey {
def getDimension(originalDimension: Dimension) = Dimension(1000,1000)
}
case object Medium extends ResizedImageKey{
def getDimension(originalDimension: Dimension) = Dimension(500,500)
}
case object Small extends ResizedImageKey{
def getDimension(originalDimension: Dimension) = Dimension(100,100)
}
我想可以在Java通过给一个实现枚举值来完成。 有没有在斯卡拉等效?
Answer 1:
这实际上是在我看来,适当的用例2.10的宏:你想访问你知道编译器的信息,但不暴露,和宏给你一个(合理的)简单的方法来偷看里面。 见我的答案在这里的相关(不过现在稍微外的日期),例如,或者只是使用是这样的:
import language.experimental.macros
import scala.reflect.macros.Context
object SealedExample {
def values[A]: Set[A] = macro values_impl[A]
def values_impl[A: c.WeakTypeTag](c: Context) = {
import c.universe._
val symbol = weakTypeOf[A].typeSymbol
if (!symbol.isClass) c.abort(
c.enclosingPosition,
"Can only enumerate values of a sealed trait or class."
) else if (!symbol.asClass.isSealed) c.abort(
c.enclosingPosition,
"Can only enumerate values of a sealed trait or class."
) else {
val children = symbol.asClass.knownDirectSubclasses.toList
if (!children.forall(_.isModuleClass)) c.abort(
c.enclosingPosition,
"All children must be objects."
) else c.Expr[Set[A]] {
def sourceModuleRef(sym: Symbol) = Ident(
sym.asInstanceOf[
scala.reflect.internal.Symbols#Symbol
].sourceModule.asInstanceOf[Symbol]
)
Apply(
Select(
reify(Set).tree,
newTermName("apply")
),
children.map(sourceModuleRef(_))
)
}
}
}
}
现在,我们可以写出如下:
scala> val keys: Set[ResizedImageKey] = SealedExample.values[ResizedImageKey]
keys: Set[ResizedImageKey] = Set(Large, Medium, Small)
而这一切都是完全安全的 - 你,如果你问的是不密封的类型的值得到一个编译时错误,具有无物的孩子,等等。
Answer 2:
基于Scala的宏,上述方案的伟大工程。 但它不喜欢的情况:
sealed trait ImageSize
object ImageSize {
case object Small extends ImageSize
case object Medium extends ImageSize
case object Large extends ImageSize
val values = SealedTraitValues.values[ImageSize]
}
为了实现这一点,我们可以使用下面的代码:
import language.experimental.macros
import scala.reflect.macros.Context
object SealedExample {
def values[A]: Set[A] = macro values_impl[A]
def values_impl[A: c.WeakTypeTag](c: Context) = {
import c.universe._
val symbol = weakTypeOf[A].typeSymbol
if (!symbol.isClass) c.abort(
c.enclosingPosition,
"Can only enumerate values of a sealed trait or class."
) else if (!symbol.asClass.isSealed) c.abort(
c.enclosingPosition,
"Can only enumerate values of a sealed trait or class."
) else {
val siblingSubclasses: List[Symbol] = scala.util.Try {
val enclosingModule = c.enclosingClass.asInstanceOf[ModuleDef]
enclosingModule.impl.body.filter { x =>
scala.util.Try(x.symbol.asModule.moduleClass.asClass.baseClasses.contains(symbol))
.getOrElse(false)
}.map(_.symbol)
} getOrElse {
Nil
}
val children = symbol.asClass.knownDirectSubclasses.toList ::: siblingSubclasses
if (!children.forall(x => x.isModuleClass || x.isModule)) c.abort(
c.enclosingPosition,
"All children must be objects."
) else c.Expr[Set[A]] {
def sourceModuleRef(sym: Symbol) = Ident(
if (sym.isModule) sym else
sym.asInstanceOf[
scala.reflect.internal.Symbols#Symbol
].sourceModule.asInstanceOf[Symbol]
)
Apply(
Select(
reify(Set).tree,
newTermName("apply")
),
children.map(sourceModuleRef(_))
)
}
}
}
}
Answer 3:
有没有能力为这个本身。 它不会在更常见的情形,而不是情况下你有实际的类作为您的密封特点的子类对象是有意义的。 它看起来像你的情况可能是由枚举来更好地处理
object ResizedImageKey extends Enumeration {
type ResizedImageKey = Value
val Small, Medium, Large = Value
def getDimension(value:ResizedImageKey):Dimension =
value match{
case Small => Dimension(100, 100)
case Medium => Dimension(500, 500)
case Large => Dimension(1000, 1000)
}
println(ResizedImageKey.values.mkString(",") //prints Small,Medium,Large
或者,你可以自己创建一个枚举,可能将其放置在同伴对象为方便
object ResizedImageKey{
val values = Vector(Small, Medium, Large)
}
println(ResizedImageKey.values.mkString(",") //prints Small,Medium,Large
Answer 4:
看到这个在另一个线程的答案 。 该Lloydmetas Enumeratum库提供了Java枚举像功能容易得到的包以相对较少的样板。
Answer 5:
看看@ TravisBrown的问题作为无形2.1.0-快照的代码张贴在他的问题的作品,并产生一个Set
,然后可以遍历枚举ADT元素。 我将在这里回顾一下他的解决方案为便于参考( fetchAll
是那种我的 :-))
import shapeless._
trait AllSingletons[A, C <: Coproduct] {
def values: List[A]
}
object AllSingletons {
implicit def cnilSingletons[A]: AllSingletons[A, CNil] =
new AllSingletons[A, CNil] {
def values = Nil
}
implicit def coproductSingletons[A, H <: A, T <: Coproduct](implicit
tsc: AllSingletons[A, T],
witness: Witness.Aux[H]
): AllSingletons[A, H :+: T] =
new AllSingletons[A, H :+: T] {
def values: List[A] = witness.value :: tsc.values
}
}
trait EnumerableAdt[A] {
def values: Set[A]
}
object EnumerableAdt {
implicit def fromAllSingletons[A, C <: Coproduct](implicit
gen: Generic.Aux[A, C],
singletons: AllSingletons[A, C]
): EnumerableAdt[A] =
new EnumerableAdt[A] {
def values: Set[A] = singletons.values.toSet
}
}
def fetchAll[T](implicit ev: EnumerableAdt[T]):Set[T] = ev.values
Answer 6:
东西也可以解决的问题是增加一个隐含的皈依添加方法,而不是iteraring在密封性状枚举的可能性。
object SharingPermission extends Enumeration {
val READ = Value("READ")
val WRITE = Value("WRITE")
val MANAGE = Value("MANAGE")
}
/**
* Permits to extend the enum definition and provide a mapping betweet SharingPermission and ActionType
* @param permission
*/
class SharingPermissionExtended(permission: SharingPermission.Value) {
val allowRead: Boolean = permission match {
case SharingPermission.READ => true
case SharingPermission.WRITE => true
case SharingPermission.MANAGE => true
}
val allowWrite: Boolean = permission match {
case SharingPermission.READ => false
case SharingPermission.WRITE => true
case SharingPermission.MANAGE => true
}
val allowManage: Boolean = permission match {
case SharingPermission.READ => false
case SharingPermission.WRITE => false
case SharingPermission.MANAGE => true
}
def allowAction(actionType: ActionType.Value): Boolean = actionType match {
case ActionType.READ => allowRead
case ActionType.WRITE => allowWrite
case ActionType.MANAGE => allowManage
}
}
object SharingPermissionExtended {
implicit def conversion(perm: SharingPermission.Value): SharingPermissionExtended = new SharingPermissionExtended(perm)
}
文章来源: Iteration over a sealed trait in Scala?