defoo
defoo

Reputation: 5297

Supplying "Class" type as a parameter to a method in Scala

I am exploring Scala by rewriting some of my Java code with it. In one of the Java method, I need to pass a class type as a parameter:

public void setType(Class<T> type)

In Java, I could do it by:

someobj.setType( MyClass.class )

But in Scala, I can't seem to call "MyClass.class". I am wondering how I can pass the parameter in Scala?

Upvotes: 4

Views: 4286

Answers (3)

Ravinder Payal
Ravinder Payal

Reputation: 3031

There's one more way to do so if you just need to pass class type and use it to model data or /create new instances.

def doSomeThing[T](id: UUID, time: Date): List[T] = {
// do anything with T, it's a reference to class definition not an instance
  List(T(id, time), T(id, new Date(time.getTime + 900 * 1000))
}
case class SomeClassA(id: UUID, time: Date)
case class SomeClassB(id: UUID, time: Date)
class NonCaseClass(p1: UUID, p2: Date)


doSomeThing[SomeClassA]()
doSomeThing[SomeClassB]()
doSomeThing[NonCaseClass]()

I have made this code little complex, here's the wrapper only example:

def doSomeThing[T]() = {
// do anything with T, it's a reference to class definition not an instance
}
case class SomeClassA(id: UUID, time: Date)

doSomeThing[SomeClassA]()

Upvotes: 0

brandon
brandon

Reputation: 675

scala> case class MyClass()
defined class MyClass

scala> def setType[T](t:Class[T]) = println(t)
setType: [T](t: Class[T])Unit

scala> setType(classOf[MyClass])
class $line23.$read$$iw$$iw$MyClass

Philippe correctly points out that the OP needs to call a Java method from Scala. In that case, more info about the java class is needed to determine intent, but something like this:

Java:

public class JavaClass<T> {
    public void setType(Class<T> type) {
        System.out.println(type);
    }
}

Scala:

class MyClass()
object classtest {
  val someobj = new JavaClass[MyClass]     //> someobj  : JavaClass[MyClass] = JavaClass@6d4c1103     
  someobj.setType(classOf[MyClass])               //> class MyClass
}

Upvotes: 0

Paul Butcher
Paul Butcher

Reputation: 10852

You're after classOf[MyClass].

Upvotes: 11

Related Questions