[英]Scala type mismatch; found : Int(0) required: Int
我在Int
包装器类下面编写了代码。
case class Wrapper[Int](value: Int) {
def map(f: Int => Int): Wrapper[Int] = Wrapper(f(value))
def flatMap(f: Int => Wrapper[Int]): Wrapper[Int] = f(value)
def filter(f: Int => Boolean): Wrapper[Int] = Wrapper(if(f(value)) 0 else value)
}
当我编译代码时,出现以下错误-
type mismatch;
[error] found : Int(0)
[error] required: Int
[error] def filter(f: Int => Boolean): Wrapper[Int] = Wrapper(if (f(value)) 0 else value)
[error] ^
[error] one error found
我找不到此错误的任何明显原因。 任何想法如何解决这个问题。
通过编写class Wrapper[Int]
,您定义了一个名为Int
的类型参数。 每当在类中编写Int
,您都将引用该类型参数,而不是实际的Int
类型。
您的定义完全与此相同:
case class Wrapper[T](value: T) {
def map(f: T => T): Wrapper[T] = Wrapper(f(value))
def flatMap(f: T => Wrapper[T]): Wrapper[T] = f(value)
def filter(f: T => Boolean): Wrapper[T] = Wrapper(if(f(value)) 0 else value)
}
而且,如果您尝试编译此版本,则会得到更容易理解的错误,即在Int
中预期有T
如果希望包装器特定于整数,则应删除type参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.