Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put methods in sets?

Tags:

scala

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 done? (without turning to maps with key return for removal, or passing around other intermediate variables)

like image 689
gwohpq9 Avatar asked Jul 04 '11 11:07

gwohpq9


1 Answers

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

like image 162
Debilski Avatar answered Oct 05 '22 05:10

Debilski