在Scala中对密封特性进行迭代?

时间:2012-12-02 17:24:06

标签: scala enumeration scala-macros sealed

我只是想知道是否可以在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中完成。 Scala中有等效的吗?

6 个答案:

答案 0 :(得分:56)

在我看来,这实际上是2.10宏的一个合适的用例:你想要访问你知道编译器有的信息,但是没有公开,而宏给你一个(合理)简单的方法来查看内部。请参阅我的回答here以获取相关(但现在稍微过时)的示例,或者只使用以下内容:

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)

这一切都非常安全 - 如果您要求未密封的类型的值,非对象子项等等,您将收到编译时错误。

答案 1 :(得分:8)

基于Scala Macros的上述解决方案效果很好。然而,它不是像:

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(_))
                )
            }
        }
    }
}

答案 2 :(得分: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

答案 3 :(得分:1)

answer in another thread。 Lloydmetas Enumeratum libraryan easily available package中提供了类似java Enum的功能,而且样板量相对较少。

答案 4 :(得分:1)

看看@ TravisBrown的question在无形的2.1.0-SNAPSHOT中,他的问题中发布的代码可以工作并生成Set枚举的ADT元素,然后可以遍历这些元素。为了便于参考,我将在此回顾他的解决方案(fetchAllsort of mine: - ))

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

答案 5 :(得分:0)

可以解决问题的是可以添加隐式转换以向枚举添加方法,而不是迭代密封特征。

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)
}