开发者

How to put methods in sets?

def m(x: Int): Any = { }
var set = new HashSet[Int => Any] 
set += m
set += m

set.size is now 2, and set.contains(m) is false, because apparently m is partially applied two times and two function objects is created. If m is a function, it works as expected. I want to treat the functions as equals if they reference the same method. Can this be don开发者_如何学JAVAe? (without turning to maps with key return for removal, or passing around other intermediate variables)


Use val fun = m _ to transform the method into a function before adding it.

Doing set += m implicitly creates a new function which is not equal to the function created when doing set.contains(m), e.g. both uses of m in a function context create a completely new and thus different function object. (Sorry, I just saw, you’ve already said that.)

This is okay, if you just need the get the methods into the set somehow and then use the set for all referencing. So the following works as well:

def m(x: Int): Any = { }
var set = new HashSet[Int => Any]
set += m
val fun = set.head // should not use head in real code but an iterator
set.contains(fun)

Addition:

or passing around other intermediate variables

There is no such thing as a method object in Scala. So I don’t think it is possible to compare two methods unless you compare their name. (Might be possible using reflection, but I’m not sure about that and it would be pretty nasty to do as well – you wouldn’t have a set of functions then but of method references which you’d need to transform to proper methods and back again.)


You can wrap the method into a lambda with the same signature:

val m1 = (i:Int) => m(i)
set += m1
set += m1
println( set.size ) // Outputs "1"
println( set contains m1 ) //Outputs "true"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜