scala - 如何修复 Scala 中的这种类型不匹配错误?

标签 scala generics types

我在 Scala REPL 中遇到以下错误:

scala> trait Foo[T] { def foo[T]:T  }
defined trait Foo

scala> object FooInt extends Foo[Int] { def foo[Int] = 0 }
<console>:8: error: type mismatch;
found   : scala.Int(0)
required: Int
   object FooInt extends Foo[Int] { def foo[Int] = 0 }
                                                   ^

我想知道它究竟意味着什么以及如何解决它。

最佳答案

您可能不需要该方法的类型参数 foo .问题是它遮蔽了它的特征 Foo 的类型参数,但不一样。

 object FooInt extends Foo[Int] { 
     def foo[Int] = 0 
          //  ^ This is a type parameter named Int, not Int the class.
 }

同样地,
 trait Foo[T] { def foo[T]: T  }
           ^ not the    ^
              same T

你应该简单地删除它:
 trait Foo[T] { def foo: T  }
 object FooInt extends Foo[Int] { def foo = 0 }

关于scala - 如何修复 Scala 中的这种类型不匹配错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29371012/

相关文章:

generics - 相互定义的参数中的 F# 通用单位

python - cubes.errors.ConfigurationError : config should be a ConfigParser instance, 但为 <type 'instance' >

Java 与 Scala 语法比较

Java 泛型,将 T 方法作为 T 而不是其父类(super class)调用

java - Scala RegEx 字符串提取器的行为不一致

c# - 如何创建一个灵活的架构,使我能够在多个不同的底层数据模型上运行?

c - 类型转换 - unsigned 到 signed int/char

c - 反转两字节长变量中的一个字节

scala - 现有答案的柯里化(Currying)函数无效

Scalameta:识别特定注释