使用理解功能的功能组合会产生Char而不是String

spa*_*rkr 2 string functional-programming scala function-composition for-comprehension

我正在尝试用于理解来构造对象调用,这是我的简单实现:

object FuncA extends (String => Int => String) {
    override def apply(str: String): Int => String = i => {
      s"${(str.toInt + i).toString}"
    }
  }

  object FuncB extends (String => Int) {
    override def apply(str: String): Int = {
      str.toInt
    }
  }

  for {
    funcAStr <- FuncA("1")(1)
    funcBStr <- FuncB(funcAStr) // Fails here
  } yield {
    println(s"Final String incremented as int is $funcBStr")
  }
Run Code Online (Sandbox Code Playgroud)

但是奇怪的是,我有一个问题,其中funcAStr被解释为Char而不是String。任何理想的原因是什么?

Tim*_*Tim 7

尽管包含了for-loop标签,但for在Scala中并未定义循环。for是定义序列的简写方式mapflatMapwithFilter电话。

您的代码转换为:

FuncA("1")(1).flatMap{ funcAStr =>
  FuncB(funcAStr).map{ funcBStr =>
    println(s"Final String incremented as int is $funcBStr")
  }
}   
Run Code Online (Sandbox Code Playgroud)

Func("1")(1)返回String。该flatMap方法对String需要依次字符串的每个字符,所以funcAStr实际上是Char没有String


Mar*_*lic 5

andThen像这样尝试功能组合

(FuncA("1") andThen FuncB)(1)
Run Code Online (Sandbox Code Playgroud)

哪个输出

res0: Int = 2
Run Code Online (Sandbox Code Playgroud)