在 Scala 中,使用 `_` 和使用命名标识符有什么区别? [英] In Scala, what is the difference between using the `_` and using a named identifier?

查看:37
本文介绍了在 Scala 中,使用 `_` 和使用命名标识符有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我尝试使用 _ 而不是使用命名标识符时会出现错误?

Why do i get an error when I try using _ instead of using a named identifier?

scala> res0
res25: List[Int] = List(1, 2, 3, 4, 5)

scala> res0.map(_=>"item "+_.toString)
<console>:6: error: missing parameter type for expanded function ((x$2) => "item
 ".$plus(x$2.toString))
       res0.map(_=>"item "+_.toString)
                           ^

scala> res0.map(i=>"item "+i.toString)
res29: List[java.lang.String] = List(item 1, item 2, item 3, item 4, item 5)

推荐答案

用于代替变量名的下划线很特殊;第 N 个下划线表示匿名函数的第 N 个参数.所以以下是等价的:

Underscores used in place of variable names like that are special; the Nth underscore means the Nth argument to an anonymous function. So the following are equivalent:

List(1, 2, 3).map(x => x + 1)

List(1, 2, 3).map(_ + 1)

但是,如果你这样做:

List(1, 2, 3).map(_ => _ + 1) 

然后您使用一个函数映射列表,该函数忽略其单个参数并返回由_ + 1 定义的函数.(此特定示例无法编译,因为编译器无法推断第二个下划线的类型.)具有命名参数的等效示例如下所示:

Then you are mapping the list with a function that ignores its single argument and returns the function defined by _ + 1. (This specific example won't compile because the compiler can't infer what type the second underscore has.) An equivalent example with named parameters would look like:

List(1, 2, 3).map(x => { y => y + 1 })

简而言之,在函数的参数列表中使用下划线意味着我忽略了这个函数体中的这些参数".在正文中使用它们意味着编译器,请为我生成一个参数列表".这两种用法不能很好地混合.

In short, using underscores in a function's argument list means "I am ignoring these arguments in the body of this function." Using them in the body means "Compiler, please generate an argument list for me." The two usages don't mix very well.

这篇关于在 Scala 中,使用 `_` 和使用命名标识符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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