Scala underscore use to simplify syntax of functio

2019-06-22 05:02发布

问题:

I have the following code:

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))

But the interpreter says:

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 :(

Best regards,

Stan

回答1:

First, note that

val m = x.min

does what you want, as does

val m = (Int.MaxValue /: x)(_ 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).

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)