Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get methods list in scala

Tags:

scala

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?

like image 903
skyde Avatar asked May 22 '10 00:05

skyde


People also ask

How do you check if an element is in a list 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.


1 Answers

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") 
like image 84
Daniel C. Sobral Avatar answered Sep 21 '22 05:09

Daniel C. Sobral