【问题标题】:How does implicit conversion kick-in in example from "Programming in Scala"?在“Scala 编程”的示例中,隐式转换如何启动?
【发布时间】:2011-05-19 18:39:42
【问题描述】:

在Programming in Scala7.8 Refactoring imperative-style code:

// Returns a row as a sequence
def makeRowSeq(row: Int) =
  for (col <- 1 to 10) yield {
    val prod = (row * col).toString
    val padding = " " * (4 - prod.length)
    padding + prod
  }
// Returns a row as a string
def makeRow(row: Int) = makeRowSeq(row).mkString
// Returns table as a string with one row per line
def multiTable() = {
  val tableSeq = // a sequence of row strings
    for (row <- 1 to 10)
    yield makeRow(row)
  tableSeq.mkString("\n")
}

看来yield makeRow(row)不知何故使用makeRowSeq 的“将行作为字符串返回”版本。这是怎么发生的?

【问题讨论】:

    标签: scala yield implicit-conversion


    【解决方案1】:

    问题是makeRowSeq 的返回值在调用mkString 之前进行评估,因此makeRow 调用实际上返回一个字符串。也就是说,它使用 Sequence 的 mkString 方法,而不是将函数应用于序列的每个单独项目。为此,您需要调用 map 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2011-10-23
      • 2018-09-16
      • 1970-01-01
      相关资源
      最近更新 更多