scala - 子类中的特定参数类型不可能

标签 scala covariance

我确实对以下代码有问题。它不编译。
有没有人知道如何在不使用 asInstanceOf[SomeImpl] 或模式匹配的情况下编译它。

我正在考虑使用上限或下限的一些类型参数。

object InherenceTryout extends App {

  import someimpl._

  val list = List(SomeImpl("A"), SomeImpl("B"))
  val result = new SomeHandler().handleBaseList(list)

  println("%s->%s" format (list, result))

}

package base {

  // Defines that a 'Base' object can create a new 
  // 'Base' object where another 'Base' object is mixed in
  // Does not define how the mixing will take place
  trait Base {
    def mix(other: Base): Base
  }

  // Defines how a default 'Base' object gets mixed into a list of 'Base' objects 
  trait BaseHandler {
    def defaultBase: Base
    def handleBaseList(list: List[Base]): List[Base] = list.map(b => b.mix(defaultBase))
  }

}

package someimpl {

  import base._

  // Some implementation of 'Base'
  // Defines how a new 'SomeImpl' object is created by mixing in another
  // 'SomeImpl' object

  // ERROR: 
  // class SomeImpl needs to be abstract, since method mix in trait Base of type (other: base.Base)base.Base is not defined 
  // (Note that base.Base does not match someimpl.SomeImpl: class SomeImpl in 
  // package someimpl is a subclass of trait Base in package base, but method parameter types must match exactly.)
  case class SomeImpl(id: String) extends Base {
      def mix(other: SomeImpl): SomeImpl = SomeImpl("[%s|%s]" format (id, other.id)) 
  }

  // Defines the default 'SomeImpl' object
  class SomeHandler extends BaseHandler {
    def defaultBase = SomeImpl("D")
  }

}

最佳答案

使用类型参数:

package base {

  trait Base[T <: Base[T]] {
    def mix(other: T): T
  }

  trait BaseHandler[T <: Base[T]] {
    def defaultBase: T
    def handleBaseList(list: List[T]): List[T] =
        list.map(b => b.mix(defaultBase))
  }

}

package someimpl {

  import base._

  case class SomeImpl(id: String) extends Base[SomeImpl] {
    def mix(other: SomeImpl): SomeImpl = SomeImpl("[%s|%s]" format (id, other.id))
  }

  class SomeHandler extends BaseHandler[SomeImpl] {
    def defaultBase = SomeImpl("D")
  }

}

关于scala - 子类中的特定参数类型不可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251347/

相关文章:

generics - .net 4 泛型问题

scala - 混合泛型类型

scala - 隐式Monoid [Int]等在哪里实现

scala - scala中的类型级别模式匹配

scala - 如何为 HH :MM:SS:Ms to value in seconds? 转换 Spark Dataframe 列

c# - 为什么协变和逆变不支持值类型

scala - 协变类型 T 出现在不变位置

scala - SBT IO.download(...) 方法显示进度

java - Scala:函数测试字符串的唯一字符

Scala 高级类型和协变