Scala underscore use to simplify syntax of function literals

可紊 提交于 2019-12-23 10:26:23

问题


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)


来源:https://stackoverflow.com/questions/5981732/scala-underscore-use-to-simplify-syntax-of-function-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!