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.
精彩评论