Scala,调用`map(f)` 与`map(v => f(v))` 时的不同行为 [英] Scala, different behaviour when calling `map(f)` vs `map(v => f(v))`
问题描述
我在调用 map(f)
和 map(v => f(v))
时得到了不同的行为.为什么?
I get a different behaviour when calling map(f)
vs map(v => f(v))
. Why?
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
推荐答案
Eta-expansion(将用作值的方法 toPrettyString
变成匿名函数)发生在类型参数推断之前,您可以认为它相当于
Eta-expansion (which turns the method toPrettyString
used as a value into an anonymous function) happens before type parameter inference, you can think of it as equivalent to
def toPrettyString1[T]: T => String =
(x: T) => toPrettyString(x)
List(entry).map(toPrettyString1)
在toPrettyString1
中,必须选择PPrint
的默认隐式实例,它只调用toString
.
in toPrettyString1
, the default implicit instance of PPrint
, which just calls toString
, has to be chosen.
在List(entry).map(e => toPrettyString(e))
中,e
的类型被推断为Entry
因此宏生成了正确的隐式.
In List(entry).map(e => toPrettyString(e))
, type of e
is inferred to be Entry
and so the macro generates the correct implicit.
https://issues.scala-lang.org/browse/SI-7641
这篇关于Scala,调用`map(f)` 与`map(v => f(v))` 时的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!