Scala,调用`map(f)` 与`map(v => f(v))` 时的不同行为 [英] Scala, different behaviour when calling `map(f)` vs `map(v => f(v))`

查看:43
本文介绍了Scala,调用`map(f)` 与`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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆