Scala 是.右=右和.左=左吗?

Scala 是.右=右和.左=左吗?,scala,scala-cats,Scala,Scala Cats,在下一个站点: 报告提出: object EitherStyle { def parse(s: String): Either[Exception, Int] = if (s.matches("-?[0-9]+")) Either.right(s.toInt) else Either.left(new NumberFormatException(s"${s} is not a valid integer.")) def reciprocal(i: Int): Eithe

在下一个站点:

报告提出:

object EitherStyle {
  def parse(s: String): Either[Exception, Int] =
    if (s.matches("-?[0-9]+")) Either.right(s.toInt)
    else Either.left(new NumberFormatException(s"${s} is not a valid integer."))

  def reciprocal(i: Int): Either[Exception, Double] =
    if (i == 0) Either.left(new IllegalArgumentException("Cannot take reciprocal of 0."))
    else Either.right(1.0 / i)

  def stringify(d: Double): String = d.toString
}
然而,我得到了一个错误:

[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:16:39: value right is not a member of object scala.util.Either
[error]     if (s.matches("-?[0-9]+")) Either.right(s.toInt)
[error]                                       ^
[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:17:17: value left is not a member of object scala.util.Either
[error]     else Either.left(new NumberFormatException(s"${s} is not a valid integer."))
[error]                 ^
[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:21:14: value left is not a member of object scala.util.Either
[error]       Either.left(new IllegalArgumentException("Cannot take reciprocal of 0."))
[error]              ^
[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:22:17: value right is not a member of object scala.util.Either
[error]     else Either.right(1.0 / i)
[error]                 ^
[error] four errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 2 s, completed Feb 12, 2020 10:25:02 AM
但是,当我用right替换任一.right,用left替换任一.left时,我编译了以下代码:

object EitherStyle {
  def parse(s: String): Either[Exception, Int] =
    if (s.matches("-?[0-9]+")) Right(s.toInt)
    else Left(new NumberFormatException(s"${s} is not a valid integer."))

  def reciprocal(i: Int): Either[Exception, Double] =
    if (i == 0)
      Left(new IllegalArgumentException("Cannot take reciprocal of 0."))
    else Right(1.0 / i)

  def stringify(d: Double): String = d.toString
}

所以,我想知道是什么让这一切发生。

这是对标准对象的扩展


导入cats.syntax.other.\u以使其正常工作。

这是对标准other对象的cats扩展

导入cats.syntax.other.\u为了使其起作用。

因此,这些被定义为扩展方法,您可以使用Import cats.syntax.other.\u将其引入范围-其用途是改进类型推断。由于Lefta返回Left[a,Nothing]类型的值,而earth.Lefta返回的值类型为earth[a,Nothing]。因此这些被定义为扩展方法,您可以使用import cats.syntax.earth.\将其用于改进类型推断。因为Lefta返回Left[a,Nothing]类型的值,而earth.Lefta返回的值类型为earth[a,Nothing]。