I want to define a function that could compare two class types. I have defined two different classes:
abstract class Task
case class DefinedTask(id: Long) extends Task
case class EmptyTask() extends Task
Then I have a function that returns an object of type Task, that could be either DefinedTask or EmptyTask.
Now, what I'd like to do is to have a function that identifies if this object is a DefinedTask or just an EmptyTask. The problem would be simple, I'd use pattern matching. But I want to generalize it because multiple classes go with this Defined/Empty pattern.
What I'd tried so far is:
def makeReturned[T: Manifest, U: Manifest](obj: T)(u: U)(f: T => Value) =
if(manifest[U] equals manifest[T]) f(obj) else
throw new IllegalArgumentException()
}
//call to it
makeReturned(task)(DefinedTask)(makeTask)
U is always DefinedTask, T could be either DefinedTask or EmptyTask, but it is returned as Task.
manifest[U].erasure.toString //"class DefinedTask$"
manifest[T].erasure.toString //"class Task"
Which is right from the compiler's stand point but it's not for me. So, my question is how could I compare them in a way that would give me what I want?
It looks like you want run-time, not compile-time checking. So I think you mean
def makeReturned[U <: Task, T <: Task](obj: T)(u: U)(f: T => Value) = {
if (obj.getClass.isInstance(u.getClass)) f(obj)
else throw new IllegalArgumentException
}
or something like that. Look at the methods on java.lang.Class and pick the one that does what you want.
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