带Scala的List.map中的下划线和字符串连接 [英] Underscores and string concatenation in List.map with Scala

查看:106
本文介绍了带Scala的List.map中的下划线和字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala可让您使用下划线来绘制简单的地图.因此,例如,而不是编写:

Scala lets you use an underscore to do a simple map. So for example instead of writing:

def roleCall(people: String*){
  people.toList.map(x => println(x))
}  

...我可以改写:

def roleCall(people: String*){
  people.toList.map(println(_))
}  

但是由于某种原因我无法写:

However for some reason I can't write:

def greet(people: String*){
  // This won't compile!
  people.toList.map(println("Hello " + _))
}

我必须写:

def greet(people: String*){
  people.toList.map(x => println("Hello " + x))
}

谁能解释为什么?

推荐答案

基本上,仅当没有嵌套括号时,函数定义的速记语法才能按预期工作.这是因为每个嵌套级别都会创建下划线所在的自己的范围.在REPL中,您可以检查例如:

Basically, the shorthand syntax for function definitions works as expected only if there are no nested parentheses. This is because each nesting level creates its own scope in which the underscores live. In the REPL, you can check for example that:

scala> val list = List(1,2,3).map(_ + 1)
list: List[Int] = List(2, 3, 4)

scala> val list = List(1,2,3).map((_ + 1))
list: List[Int] = List(2, 3, 4)

都可以,但是一旦在括号后添加任何内容,就会出现错误:

both work, but once you add anything after the parentheses, you get an error:

val list = List(1,2,3).map((_ + 1) + 1)
<console>:58: error: missing parameter type for expanded function ((x$1) => x$1.$plus(1))
       val list = List(1,2,3).map((_ + 1) + 1)

如您所见,该错误仅与函数(_ + 1)(在消息中显示为((x$1) => x$1.$plus(1)))有关,而不与整个表达式(_ + 1) + 1有关,因此括号中的部分被视为单独的函数,并且下划线_在此内部函数的范围内解释,而不是在外部函数的范围内.

As you see, the error pertains only to the function (_ + 1) (shown as ((x$1) => x$1.$plus(1)) in the message), not to the whole expression (_ + 1) + 1 so the part in parentheses is treated as a separate function and the underscore _ is interpreted in the scope of this inner function, not the external one.

我不太确定为什么List(1,2,3).map(println(_))可以工作,但是似乎是一个极端的情况,由于单个参数,这似乎只是巧合.我很高兴自己学习细节.无论如何,将匿名函数定义内的括号与下划线一起使用,势必迟早会引起麻烦,最好避免这种情况.

I'm not really sure why List(1,2,3).map(println(_)) works but it seems to be some edge case which due to the single argument seems to just work by mere coincidence. I'd be happy myself to learn the details. Anyway, using parentheses inside anonymous function definitions with underscores is bound to cause trouble sooner or later and it's better to avoid it.

这篇关于带Scala的List.map中的下划线和字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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