Scala 通用推理

标签 scala generics

我希望对具有作为 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)))

我要补充一点,我明确需要知道 AaS 类型以便稍后重用它们。

是否有任何解决方案可以让用户放置这些通用类型。如果没有,我会很高兴知道原因。

最佳答案

您可以简化 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)))

工作卡斯蒂:https://scastie.scala-lang.org/fmOLxCiKRBKIDFSj7stZNQ

关于Scala 通用推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389651/

相关文章:

Swift 对类型的泛型约束

typescript - 在 TypeScript 条件类型中,如何测试函数/泛型参数的存在?

scala - mllib Vector 的最大值?

multithreading - 多线程中未知进程的高CPU使用率

scala - 在没有隐式证据对象的情况下直接使用 Scala 类型类

c# - 实现接口(interface)的泛型列表

Java - 如何对通用 ArrayList 进行子类化,以便 MyArrayList<foo> 的实例成为 ArrayList<foo> 的子类?

scala - Clojure 相当于 Scalaz Foldable 的折叠图是什么?

scala - Scala 中是否可以等于抽象类型成员?

java - 一般错误 :class is not applicable for the arguments