在Scala中如何迭代一个封闭的特质?

41

我只是想知道在Scala中是否可以迭代封闭的特质(sealed trait)?如果不行,为什么不行呢?既然该特质已被封闭,那应该是可以的,对吗?

我的需求是这样的:

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中有相应的功能吗?


1
这不是你想要的吗?链接 - Tomasz Nurkiewicz
谢谢!我试图理解为什么我不能使用case对象 ;) - Sebastien Lorber
6个回答

66

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

这一切都是完全安全的——如果您请求一个非封闭类型、具有非对象子元素等内容,您将在编译时收到错误提示。


6
是的,Java的 enum 相对于Scala的 Enumeration 来说可能会更不那么混乱,并且在这个特定方面上比封闭的特质更加方便,但是我仍然会选择Scala的类似代数数据类型(ADT)的方法而非 enum - Travis Brown
5
实际上,这个宏存在一个问题,如http://stackoverflow.com/questions/18732362/issue-with-using-macros-in-sbt所指出的。它的最后几行应该替换为https://gist.github.com/xeno-by/6573434。 - Eugene Burmako
3
已修复(最终-对于没有及时注意到评论,我表示歉意)。谢谢,尤金! - Travis Brown
2
这个宏对我不起作用。我使用的是scala 2.11.2SealedExample.values [Rank]我得到了:类型不匹配;找到:scala.collection.immutable.Set [Product with Serializable with Rank]需要:Set [Rank]注意:Product with Serializable with Rank <: Rank,但Set特质在类型A中是不变的。您可能希望调查通配符类型,例如“_ <: Rank”。(SLS 3.2.10)sheet.sc / playground / src第8行Scala问题 - Anton Kuzmin
8
在得到@TravisBrown的批准后,我刚刚将这个答案打包成一个小库,并发布到了Bintray上。来源:https://github.com/mrvisser/sealerate Bintray:https://bintray.com/pellucid/maven/sealerate/view/general - mrvisser
显示剩余7条评论

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

5

请看@TravisBrown的问题。自从shapeless 2.1.0-SNAPSHOT发布以来,他在问题中发布的代码可以运行并生成一个枚举ADT元素的Set,然后可以遍历该集合。为了方便参考,我将在此重述他的解决方案(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

我想补充你的答案,即我们不需要使用隐式实现EnumerableAdt[T]来为某些特征T进行实现。一切都将仅因宏生成而正常工作。我认为这一点在这里并不明显。 - Boris Azanov

3

这种功能本地是没有的。在更常见的情况下,你的封闭 trait 的子类实际上是实际类而不是 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

1

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接