scala - 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#Persist
as 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
解决方案
这失败了,因为PE.this.Persist
它是的子类型,PE#Persist
因此您试图传递需要特定子类型的超类型。
当类型像这样嵌套时,Scala 为封闭类的每个实例创建一个新的嵌套类型。因此,Persist
使用 的一个实例创建的实例与使用 的不同实例创建PE
的实例不兼容。该符号表示所有不同类型的超类型。Persist
PE
PE#Persist
PE.this.Persist
推荐阅读
- java - 有没有办法为 java Swing 应用程序设置默认鼠标光标图像?
- angular - 'new FormControl',对于反应形式是强制性的 - Angular
- .net - 带有 AJAX 的 ASP.NET 是否可以在 iOS(Safari、Chrome 等)上运行?
- r - 替换字符串中的第二个标点符号?
- angularjs - Docker COPY 不会复制应用程序中的某些文件
- wordpress - VestaCP下的域困难情况
- sql - 获取最小值并集的最大值的sql字符串
- ios - CAShapeLayer 更改 lineWidth 导致崩溃
- oracle - 'Oracle.DataAccess, Version=2.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342' 或其依赖项之一
- python - 如何在点击时获得最近的 tkinter 画布元素?