无法使用 cats 库在函数中调用 map 方法

Can't call map method in function with cats library

我正在阅读 Advanced Scala With Cats。我在仿函数描述(第 59 页)中坚持这个例子:

object FunctorsDemo extends App {

  import cats.instances.function._
  import cats.syntax.functor._

  val func1 = (x: Int) => x.toDouble
  val func2 = (y: Double) => y * 2

  val func3 = func1.map(func2) // wrong line for me

}

书中一切正常,但我有这个例外:

Error:(10, 21) value map is not a member of Int => Double
  val func3 = func1.map(func2)

不明白我做错了什么。

您在 Scala 的类型推断中遇到了一个错误,部分统一错误。

将此添加到您的 build.sbt

scalacOptions += "-Ypartial-unification"

如果您有兴趣,这里有一篇很好的文章:https://gist.github.com/djspiewak/7a81a395c461fd3a09a6941d4cd040f2

这是一种配置,具有适用的确切版本号:

build.sbt:

libraryDependencies += "org.typelevel" %% "cats-core" % "1.1.0"
scalaVersion := "2.12.5"
scalacOptions += "-Ypartial-unification"

代码(FunctionIntDoubleFunctor.scala 在与 build.sbt 相同的目录中):

object FunctionIntDoubleFunctor {

  def main(args: Array[String]) {
    import cats.syntax.functor._

    import cats.instances.function._

    val func1 = (x: Int) => x.toDouble
    val func2 = (y: Double) => y * 2


    val func3 = func1.map(func2)
    println(func3(21)) // prints 42.0
  }

}

Ammonite with @ interp.configureCompiler(_.settings.YpartialUnification.value = true) 在完全相同的代码上惨败,我不知道为什么,所以可能与您使用的工具有关。