41

我只是想知道是否可以在 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中是否有等价物?

4

6 回答 6

65

在我看来,这实际上是 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)

这一切都是非常安全的——如果你请求一个不是密封的类型的值,你会得到一个编译时错误,有非对象的孩子,等等。

于 2012-12-02T18:48:12.563 回答
8

上面提到的基于 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(_))
                )
            }
        }
    }
}
于 2014-07-11T19:27:39.773 回答
5

看看@TravisBrown 的问题截至无形 2.1.0-SNAPSHOT 中发布的代码在他的问题中起作用并产生一个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
于 2017-04-27T13:03:35.343 回答
3

本机没有此功能。在更常见的情况下没有意义,在这种情况下,您将实际类作为密封特征的子类,而不是 case 对象。看起来您的案例可能会更好地通过枚举处理

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
于 2012-12-02T17:51:56.180 回答
1

在另一个线程中查看此答案。Lloydmetas Enumeratum 库在一个易于使用的包中提供了类似 java Enum 的功能,并且样板文件相对较少。

于 2015-02-17T19:51:06.887 回答
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)
}
于 2013-07-22T08:21:38.287 回答