命名参数中的下划线 [英] Underscore in Named Arguments
问题描述
有人能解释一下这里到底发生了什么吗?我现在还没有完全投入进去:
Can someone explain me what exactly is going on here? I am not fully getting into it right now:
val s = Seq(1D,2D,3D,4D)
case class WithUnit(value: Double, unit: String)
s map { WithUnit(_,"cm") } // works
s map { WithUnit(value = _ , unit = "cm") } // error: missing parameter type for expanded function ((x$2) => value = x$2)
我猜编译器无法推断参数类型,因为我写了参数的名称.但为什么不呢?不应该仅仅因为说出参数的名称而变得更难吗?!
I guess the compiler can´t infer the parameter type because I wrote the name of the argument. But why not? It shouldn´t be more difficult only because of stating the name of the argument?!
谢谢!
推荐答案
当你写道:
WithUnit(value = _, unit = "cm")
你希望它的意思是:
x => WithUnit(value = x, unit = "cm")
但是,如果您仔细查看错误消息,您会发现编译器并没有这么看,而是将其解析为:
But if you take a close look at the error message, you'll see that the compiler didn't see it that way, it parsed it as:
WithUnit(x => value = x, unit = "cm"})
如您所见,_ 的范围比您想要的更紧密.
As you can see, the _ is scoped more tightly than you wanted.
_ 总是选择最紧密的非退化范围.作用域纯粹是在语法上确定的,在解析过程中,不考虑类型.
_ always picks the tightest non-degenerate scope it can. The scope is determined purely syntactically, during parsing, without regard to types.
非退化,我的意思是编译器没有认为你的意思是:
By non-degenerate, I mean that the compiler didn't think you meant:
WithUnit(value = x => x, unit = "cm")
Tightest non-degenerate scope 是指由最里面的函数括号相对于下划线定义的范围.如果没有这样的规则,编译器将无法知道嵌套函数调用时哪个 _ 对应哪个函数.
Tightest non-degenerate scope means the scope defined by the innermost function parenthesis relative to the underscore. Without such a rule the compiler wouldn't be able to know which _ corresponds to which function when functions calls are nested.
这篇关于命名参数中的下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!