Dave
Dave

Reputation: 2073

How do I match java.lang.Object with Scala pattern matching

I'm trying to use Scala to find the base class (other than java.lang.Object) of a sequence of Java classes. I have defined a recursive function:

def baseClass(cls: Class[_]): Class[_] = {
  val nextClass = cls.getSuperclass
  nextClass match {
    case java.lang.Object => cls 
    case _ => baseClass(nextClass)
  }
}

The compiler gives the following error: error: object Object is not a value

How to I properly terminate the recursion and return the class just below java.lang.Object?

Upvotes: 0

Views: 1272

Answers (1)

Ivan Meredith
Ivan Meredith

Reputation: 2222

scala> (new Object) match { case o: Object => "hi" }
res2: java.lang.String = hi

Except that that doesnt help you since Object is a superclass of what you are matching on.

This function does what you want.

def baseClass(cls: Class[_]): Class[_] = { 
  val nextClass = cls.getSuperclass
  println(nextClass)
  if(classOf[Object] == nextClass)
    cls
  else {
    baseClass(nextClass)
  }
}

scala> baseClass(classOf[java.util.ArrayList[_]])
class java.util.AbstractList
class java.util.AbstractCollection
class java.lang.Object
res9: java.lang.Class[_] = class java.util.AbstractCollection

Upvotes: 3

Related Questions