我有以下代码,不编译:
object CatsValidation {
type FormData = Map[String, String]
type FailFast[A] = Either[List[String], A]
type NumFmtExn = NumberFormatException
def getValue(name: String)(data: FormData)
: FailFast[String] =
data.get(name)
.toRight(List(s"$name field not specified."))
def readName(data: Map[String, String])
: FailFast[String] =
getValue("name")(data)
.flatMap(nonBlank("name")(_))
def readAge(data: Map[String, String])
: FailFast[Int] =
getValue("age")(data)
.flatMap(parseInt)
.flatMap(nonNegative("age")(_))
def parseInt(number: String)
: FailFast[Int] =
Either.catchOnly[NumFmtExn](number.toInt)
.leftMap(_ => List(s"$number must be an integer"))
def nonBlank(name: String)(data: String): FailFast[String] =
Right(data).
ensure[List[String]](List(s"$name cannot be blank"))(_.nonEmpty)
def nonNegative(name: String)(data: Int): FailFast[Int] =
Right(data).
ensure[List[String]](List(s"$name must be non-negative"))(_ >= 0)
def main(args: Array[String]): Unit = {
println(nonBlank("name")("Dade Murphy"))
// res36: FailFast[String] = Right(Dade Murphy)
println(nonBlank("name")(""))
// res37: FailFast[String] = Left(List(name cannot be blank))
println(nonNegative("age")(11))
// res38: FailFast[Int] = Right(11)
println(nonNegative("age")(-1))
// res39: FailFast[Int] = Left(List(age must be non-negative))
}
}
错误消息是:
Error:(36, 13) type arguments [List[String]] do not conform to method ensure's type parameter bounds [AA >: A]
ensure[List[String]](List(s"$name cannot be blank"))(_.nonEmpty)
Error:(40, 13) type arguments [List[String]] do not conform to method ensure's type parameter bounds [AA >: A]
ensure[List[String]](List(s"$name must be non-negative"))(_ >= 0)
为什么类型不正确?
答案 0 :(得分:0)
Left
Right(...)
类型丢失了
明确设置类型:
def nonBlank(name: String)(data: String): FailFast[String] =
Right[List[String], String](data).
ensure[List[String]](List(s"$name cannot be blank"))(_.nonEmpty)
def nonNegative(name: String)(data: Int): FailFast[Int] =
Right[List[String], Int](data).
ensure[List[String]](List(s"$name must be non-negative"))(_ >= 0)