In language like python and ruby to ask the language what index-related methods its string class supports (which methods’ names contain the word “index”) you can do
“”.methods.sort.grep /index/i
And in java
List results = new ArrayList();
Method[] methods = String.class.getMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
if (m.getName().toLowerCase().indexOf(“index”) != -1) {
results.add(m.getName());
}
}
String[] names = (String[]) results.toArray();
Arrays.sort(names);
return names;
How would you do the same thing in Scala?
Curious that no one tried a more direct translation:
So, some random thoughts.
The difference between “methods” and the hoops above is striking, but no one ever said reflection was Java’s strength.
I’m hiding something about
sortedabove: it actually takes an implicit parameter of typeOrdering. If I wanted to sort the methods themselves instead of their names, I’d have to provide it.A
grepis actually a combination offilterandmatches. It’s made a bit more complex because of Java’s decision to match whole strings even when^and$are not specified. I think it would some sense to have agrepmethod onRegex, which tookTraversableas parameters, but…So, here’s what we could do about it:
And now this is possible: