在“Scala 编程”的示例中,隐式转换如何启动?
// 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)
不知何故使用了“Returns a row as a makeRowSeq
的 string' 版本。这是怎么发生的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,
makeRowSeq
的返回值是在调用mkString
之前评估的,因此makeRow
调用实际上返回一个字符串。也就是说,它使用 Sequence 的 mkString 方法,而不是将该函数应用于序列的每个单独项目。为此,您需要调用地图函数。The thing is that the return from
makeRowSeq
is evaluated before the call tomkString
so that themakeRow
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.