Scala下划线用于简化函数文字的语法 [英] Scala underscore use to simplify syntax of function literals
问题描述
我有以下代码:
var x = Array(1,3,4,4,1,1,3)
var m = Int.MaxValue
x.foreach((x)=>(m = m min x))
我试图将最后一句话简化为:
I tried to simplify last sentence to:
x.foreach((m = _ min m))
但是口译员说:
scala> x.foreach((m = _ min m))
<console>:8: error: missing parameter type for expanded function ((x$1) => x$1.min(m))
x.foreach((m = _ min m))
^
我试图更明确地说明类型:
I tried to be more explicit about the type:
scala> x.foreach((m = (_:Int) min m))
<console>:8: error: type mismatch;
found : (Int) => Int
required: Int
x.foreach((m = (_:Int) min m))
^
我和编译器彼此不了解:(
The compiler and I don't understand each other :(
最诚挚的问候,
斯坦
推荐答案
首先,请注意
val m = x.min
做您想做的事,
val m = (Int.MaxValue /: x)(_ min _)
我将留给您阅读有关这些内容的更多信息(关于集合和折叠的min方法;请注意,这些方法的速度不如您所写的那么快).
I will leave it to you to read more about these things (the min method on collections, and folds; note that these are not quite as fast as what you wrote).
问题在于,当您编写下划线时,编译器会迷失了您的意思和有效类型,而当您添加类型信息时,编译器会认为您正在尝试编写函数在那里并将其分配给m
.但是,当然m
是Int
,而不是函数,因此它会抱怨.
The problem is that the compiler is getting lost with what you mean and with what valid types might be when you write the underscore, and when you add the type information it thinks that you're trying to write a function right there and assign it to m
. But of course m
is an Int
, not a function, so it complains.
只需明确地编写它即可.只是几个额外的字符:
Just write it explicitly. It's only a few extra characters:
x.foreach(i => m = m min i)
这篇关于Scala下划线用于简化函数文字的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!