Scala,调用`map(f)`vs`map(v => f(v))`时的不同行为

时间:2016-10-14 17:49:55

标签: scala

调用map(f) vs map(v => f(v))时,我会遇到不同的行为。为什么呢?

libraryDependencies += "com.lihaoyi" %% "pprint" % "0.4.1"

case class Entry(id: Int, text: String)
val entry = Entry(1, "hello")

def toPrettyString[T](o: T)(implicit pp: pprint.PPrint[T]) =
  pprint.tokenize(o)(pp).mkString

println(toPrettyString(entry))                            // I get Entry(1, "hello"), as expected

List(entry).map(toPrettyString).foreach(println)          // I get Entry(1,hello), not what I want
List(entry).map(e => toPrettyString(e)).foreach(println)  // I get Entry(1, "hello"), as expected

1 个答案:

答案 0 :(得分:1)

Eta-expansion(将用作值的方法toPrettyString转换为匿名函数)在类型参数推断之前发生,您可以将其视为等效于

def toPrettyString1[T]: T => String = 
  (x: T) => toPrettyString(x)

List(entry).map(toPrettyString1)
<{1>}中的

,必须选择toPrettyString1的默认隐式实例,只需调用PPrint

toString中,List(entry).map(e => toPrettyString(e))的类型被推断为e,因此宏会生成正确的隐式。

https://issues.scala-lang.org/browse/SI-7641