无法在cat库中调用map方法

问题描述 投票:5回答:2

我正在阅读高级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 scala-cats
2个回答
2
投票

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

将此添加到您的build.sbt

scalacOptions += "-Ypartial-unification"

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


3
投票

这是一个配置,其中包含适用的确切版本号:

build.sbt:

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

代码(FunctionIntDoubleFunctor.scalabuild.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)的亚扪人在完全相同的代码上失败了,我不知道为什么,所以也许它与你正在使用的工具有关。

© www.soinside.com 2019 - 2024. All rights reserved.