Alex Rivera | Logout

How to get methods list in scala

Asked 2010-05-22T00:37:56.770
36

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?

Edit
Report

3 Answers

5

More or less the same way:

val names = classOf[String].getMethods.toSeq.
    filter(_.getName.toLowerCase().indexOf(“index”) != -1).
    map(_.getName).
    sort(((e1, e2) => (e1 compareTo e2) < 0))

But all on one line.

To make it more readable,

val names = for(val method <- classOf[String].getMethods.toSeq
    if(method.getName.toLowerCase().indexOf("index") != -1))
    yield { method.getName }
val sorted = names.sort(((e1, e2) => (e1 compareTo e2) < 0))
answered 2010-05-22T00:51:42.337
4

This is as far as I got:

"".getClass.getMethods.map(_.getName).filter( _.indexOf("in")>=0)  

It's strange Scala array doesn't have sort method.

edit

It would end up like.

"".getClass.getMethods.map(_.getName).toList.sort(_<_).filter(_.indexOf("index")>=0)
answered 2010-05-22T01:13:49.637
1

Just using the Java code direct will get you most of the way there, as Scala classes are still JVM ones. You could port the code to Scala pretty easily as well, though, for fun/practice/ease of use in REPL.

answered 2010-05-22T00:55:08.040

Your Answer