我正在阅读 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
}
在书中一切都很好,但我有这个异常(exception):
Error:(10, 21) value map is not a member of Int => Double
val func3 = func1.map(func2)
无法理解我做错了什么。
最佳答案
这是一种具有其适用的确切版本号的配置:
构建.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
}
}
菊石与
@ interp.configureCompiler(_.settings.YpartialUnification.value = true)
在完全相同的代码上惨遭失败,我不知道为什么,所以可能与您使用的工具有关。
关于scala - 无法在带有cats库的函数中调用map方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52355375/