首页 > 解决方案 > Scala 内部类泛型边界

问题描述

我有与此类似的外部 API 设置:

abstract class PE {
  type Event

  abstract class C[R] {
    def reply(r: R)
    def persist[B <: Event](e: B)(callback: B => Unit): Persist
    def fail(error: Throwable): Persist
  }
  abstract class Persist {
    // ...
  }
}

我想基于 scala 的 Try 类创建一个更像功能的包装器。我想出了以下代码:

def tryPersist[P <: PE, E <: P#Event, R](c: PE#C[R], tryEvent: Try[E])(replyProducer: E => R): PE#Persist = {
    tryEvent match {
        case Success(event) =>
            c.persist(event)(_ => c.reply(replyProducer(event)))
        case Failure(exception) =>
            c.fail(exception)
    }
  }

但是,这不起作用,因为 scala 拒绝接受PE#Persistas PE.this.Persist。有什么遗漏吗?

inferred type arguments [E] do not conform to method persist's type parameter bounds [B <: _1.Event] c.persist(event)(_ => c.reply(replyProducer(event)))

并在通话地点:

[error]  found   : MyPEImpl#Persist
[error]  required: MyPEImpl.this.Persist
[error]                     persistEvent(ctx, command.eventFor(state))(_.playerBet)

PS:如果有人注意到,是的,它是 Lagom PersistentEntity 的 API

标签: scalagenericsinner-classes

解决方案


这失败了,因为PE.this.Persist它是的子类型,PE#Persist因此您试图传递需要特定子类型的超类型。

当类型像这样嵌套时,Scala 为封闭类的每个实例创建一个新的嵌套类型。因此,Persist使用 的一个实例创建的实例与使用 的不同实例创建PE的实例不兼容。该符号表示所有不同类型的超类型。PersistPEPE#PersistPE.this.Persist


推荐阅读