【问题标题】:Scala composition of generic types泛型类型的 Scala 组合
【发布时间】:2019-06-27 20:48:31
【问题描述】:

我有一个泛型类型的复杂用例,已在下面进行了简化

trait A
class AB extends A{
  val v = 10
}

trait X[T<:A]{
  def request: T
}

class XY extends X[AB]{
  def request = new AB()
}
class Test extends App{

  /**
    * X[A]
    * X[AB]
    * XY[A]
    * XY[AB]
    */
  def test[C<:A, D <: X[C]](t:Int)(input: D): Unit ={
    print(input.getClass.getName)
  }
  implicit val req = new XY()
  test(2)(req)

}

测试方法应该支持注释部分定义的类型场景。我收到以下编译错误。

Error:(33, 7) inferred type arguments [XY] do not conform to method test's type parameter bounds [D <: X[Nothing]] test(2)(req)

这在语法上合法吗? 提前致谢。

【问题讨论】:

  • 除非它是简化的一部分,否则如果D 仅用于签名一次,则可以将其删除:test[C&lt;:A](t:Int)(input: X[C])

标签: scala generics


【解决方案1】:

编译器无法通过这样的定义分两步推断C 的类型。

所以要么让编译器在 1 步中完成,通过在 input 参数的定义中同时包含 DC

def test[C <: A, D <: X[C]](t: Int)(input: D with X[C]): Unit

或者有 D &lt;: X[C] 的隐含证据,这将帮助编译器分两步推断 C

def test[C <: A, D <: X[_]](t: Int)(input: D)(implicit ev: D <:< X[C]): Unit

【讨论】:

    【解决方案2】:

    Nothing in compile error 通常意味着某些类型没有被推断出来。

    尝试显式指定类型参数

    test[AB, XY](2)(req)
    

    Generic nested type inference works with arity-2 but not with currying

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2020-06-04
      • 2015-07-09
      • 2020-03-27
      • 2012-11-16
      相关资源
      最近更新 更多