scala - Scala 中匹配类型约束失败

标签 scala

我正在尝试在 Scala 2.9.2 中创建一个映射包装器,其中的值具有特定的更高类型,并且正在与类型系统进行斗争。这是用于说明问题的代码的精简版本:

trait A

trait B[C] {
  def c: C
}

trait E[C <: B[C], D <: A]

case class MyMap[M <: A, L <: B[L], N[L, M]](map: Map[M, N[L, M]])

object MyMap {
  def empty[M <: A, L <: B[L], N[L, M]] = MyMap(Map.empty[M, N[L, M]])
}

val myMap = MyMap.empty[A, T forSome { type T <: B[T] }, E]

当我尝试编译它时,最后一个语句失败并出现编译器错误,表明我不匹配类型边界。然而对我来说,看起来就像是这样,也许我有 N[L, M] 和之前的 L <: B[L],这并不能推断 N[L, M] 中的 L 是相同的 L < :B[L],M同理,错误如下:

kinds of the type arguments (A,T forSome { type T <: B[T] },E) do not conform to the expected kinds of the type parameters (type M,type L,type N). E's type parameters do not match type N's expected parameters: type C's bounds >: Nothing <: B[C] are stricter than type L's declared bounds >: Nothing <: Any, type D's bounds >: Nothing <: A are stricter than type M's declared bounds >: Nothing <: Any

val myMap = MyMap.empty[A, T forSome { type T <: B[T] }, E]

非常感谢您提出的任何建议。

谢谢-

最佳答案

第二个参数有一个问题,第三个参数也有一个问题。我不知道第二个参数,我不确定existentia在这里允许什么。所以这就是第三个参数的问题。

一些更简单的代码,但有相同的错误:

class A {}

class C[X <: A] {}

def f[X[_]] = 12

f[List]
res1: Int12
f[C]
error: kinds of the type arguments (C) do not conform to 
the expected kinds of the type parameters (type X).
C's type parameters do not match type X's expected parameters: 
    type X's bounds >: Nothing <: A are stricter 
    than type _'s declared bounds >: Nothing < : Any
       f[C]
         ^

很简单,方法empty需要一个带有两个参数且没有任何限制的泛型类型作为第三个类型参数。在空的正文中,您可以编写N[Int, String]或其他内容。类型 E 有一些限制,与此不兼容(注意:我发现写的是 N[L,M] 而不是 N[_, _] ,其中 LM 之前类型参数的名称有点误导。或者可能表明您并不真正想要更高阶的类型参数) .

如果你写上面的代码

def g[X[_ <: A]] = 13

然后调用g[C]就可以了(g[List]也可以,因为它应该,那里不会发生任何错误)。

类似地,如果为空,您的代码将起作用(前提是您传递合适的第二个参数)

Map.empty[M <: A, L <: B[L], N[X <: B[X], Y <: A]]

关于scala - Scala 中匹配类型约束失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12863331/

相关文章:

scala - 是否有等效的 Java Sound API?

scala - Spark.sql 或 df.filter ("").select ("") 哪个更快。使用斯卡拉

scala - 如何拥有具有多个 Scala 版本的 SBT 子项目?

scala - scala 中参数列表之前的 case 类中的 [] 这些括号有什么用

scala - 使用子类 (cats/scalaz) 使用 Functor 调用泛型函数

scala - 使用 Redis 示例提升

scala - (案例)类构造函数上下文中的隐式转换

Scala:覆盖返回 null 的通用 Java 方法

mysql - MySQL : ClassNotFoundException on driver 的 Slick 2.1 代码生成器

xml - 用scala以编程方式替换xml值