简体   繁体   中英

How does implicit conversion kick-in in example from “Programming in Scala”?

In Programming in Scala 7.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")
}

It appears that yield makeRow(row) somehow uses the 'Returns a row as a string' version of makeRowSeq . How does this happen?

The thing is that the return from makeRowSeq is evaluated before the call to mkString so that the makeRow call is actually returning one string. That is, it's using Sequence's mkString method instead of applying the function to each individual item of the sequence. To do that you'd need a map function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM