【问题标题】:Cast Type Alias to generic type without the use of package object在不使用包对象的情况下将类型别名转换为泛型类型
【发布时间】:2015-09-21 19:27:44
【问题描述】:

我目前正在编写一个存储库actor,它的工作方式类似于通常的 List 集合,但在删除时不会将元素向左移动一个位置。因此使用数组。 此存储库将允许的唯一类型是同时扩展 Actor 和 Indexable 类型的类型。我想使用类型别名作为这种类型条件的快捷方式。如何在不使用包对象的情况下将类型别名转换为类声明中的泛型类型,如下所示? (参见第 2 行和第 7 行)

package object model {
    type Mob = Actor with Indexable

    object IndexableRepository {
        def create[T <: Mob](capacity : Int) = Props(new IndexableRepository[T](capacity))
    }

    final class IndexableRepository[T <: Mob](val capacity : Int) extends Actor {
        private var indexables = new Array[Mob](capacity)

        def receive : Actor.Receive = {
            case _ => unhandled()
        }

        private def findAvailable(indexables : Seq[Mob]) = {
            (0 to indexables.size) find { idx => indexables(idx) == null }
        }
    }
}

【问题讨论】:

    标签: scala generics akka type-alias


    【解决方案1】:

    在伴生对象中声明类型别名怎么样:

    import akka.actor.{Props, Actor}
    import IndexableRepository._
    
    final class IndexableRepository[T <: Mob](val capacity : Int) extends Actor {
      private var indexables = new Array[Mob](capacity)
    
      def receive : Actor.Receive = {
        case _ => unhandled()
      }
    
      private def findAvailable(indexables : Seq[Mob]) = {
        (0 to indexables.size) find { idx => indexables(idx) == null }
      }
    }
    
    object IndexableRepository {
      type Mob = Actor with Indexable
    
      def create[T <: Mob](capacity : Int) = Props(new IndexableRepository[T](capacity))
    }
    

    不过,我认为Actor 实例并不意味着在任何地方都可以引用。将它们存储在一个集合中看起来有些可疑。

    【讨论】:

    • 我试过了。将类型别名存储在伴随对象中不起作用,因为它找不到它。将演员存储在一个集合中看起来很可疑是什么意思?此存储库本身不会创建参与者。它们是在传递到此存储库之前在外部创建的。这个存储库参与者是出于测试目的,因为我正在寻找更好的选项,例如自定义路由器。
    • @ExecutorService 我添加了一些导入。如果导入伴随对象,编译器会找到类型别名。至于“可疑”,您应该只通过ActorRef 与演员互动。您不应该通过Actor 的引用直接公开任何其他类型的 API。你如何获得参考资料。因为,afaik 你不能直接实例化它们,这也不是偶然的。如果你知道你在做什么,你可能会没事的。否则,我建议阅读 akka 文档。
    • 哦,简单的导入。谢谢。这个存储库由另一个参与者监督,它为它分配一个类型,如下所示:private val someRepository = context actorOf(IndexableRepository.create[SomeIndexable](SIZE))。之后,我将允许存储库接收消息以将参与者添加到集合中。要添加的演员当然包含在消息本身中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多