Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala underscore use to simplify syntax of function literals

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

like image 455
Stan Avatar asked Oct 12 '22 01:10

Stan


1 Answers

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)
like image 73
Rex Kerr Avatar answered Jan 01 '23 09:01

Rex Kerr