我希望对具有作为 A
后代的对象序列 s
的类进行自动类型推断,知道 A
需要通用参数。
class A[F](val field1: F)
class G[F, Aa <: A[F], S <: Seq[Aa]](val s: S) {
// what i have to do
}
// Evrything is ok
val gWith = new G[Int, A[Int], List[A[Int]]](List(new A(5)))
// Compilator failed: inferred type arguments [Nothing,Nothing,List[A[Int]]]
val gWithout = new G(List(new A(5)))
我要补充一点,我明确需要知道 Aa
和 S
类型以便稍后重用它们。
是否有任何解决方案可以让用户放置这些通用类型。如果没有,我会很高兴知道原因。
最佳答案
您可以简化 G
类的类型参数:
class A[F](val field1: F)
class B[F](override val field1: F) extends A[F](field1)
// Make A covariant
class G[F, S[+A] <: Seq[A]](val s: S[A[F]]) { }
// Everything is ok
val gWith = new G[Int, List](List(new A(5)))
// Also ok
val gWithout = new G(List(new A(5)))
// Ok too
val gBWithout = new G(List(new B(5)))
关于Scala 通用推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389651/