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?
contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element.
Curious that no one tried a more direct translation:
"" .getClass.getMethods.map(_.getName) // methods .sorted // sort .filter(_ matches "(?i).*index.*") // grep /index/i
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 sorted
above: it actually takes an implicit parameter of type Ordering
. If I wanted to sort the methods themselves instead of their names, I'd have to provide it.
A grep
is actually a combination of filter
and matches
. 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 a grep
method on Regex
, which took Traversable
as parameters, but...
So, here's what we could do about it:
implicit def toMethods(obj: AnyRef) = new { def methods = obj.getClass.getMethods.map(_.getName) } implicit def toGrep[T <% Traversable[String]](coll: T) = new { def grep(pattern: String) = coll filter (pattern.r.findFirstIn(_) != None) def grep(pattern: String, flags: String) = { val regex = ("(?"+flags+")"+pattern).r coll filter (regex.findFirstIn(_) != None) } }
And now this is possible:
"".methods.sorted grep ("index", "i")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With