How to write an isInstanceOf method?


#1

I want to write an `isInstanceOf`` method like the one included in AssertJ. In Java it would look like this:

public class Test {

  public static void main(String ...args) {
    System.out.println(isInstanceOf(new A(), B.class));
  }

  // this method in Kotlin?
  public static <T> boolean isInstanceOf(Object object, Class<T> expectedClass) {
    return expectedClass.isInstance(object);
  }

  static class A {}
  static class B extends A {}
}

How would you translate this to Kotlin?


#2

I think the literal translation would be something like this, in case you want to make it an extension function:

fun main(args: Array<String>) {
    print(A().isInstanceOf(B::class.java))
}

fun <T> Any.isInstanceOf(expectedClass: Class<T>) = expectedClass.isInstance(this)

open class A {}
class B : A() {}

Although most likely you could improve some things, for example you don’t really care about the type, so you could remove T in favour of *.

fun Any.isInstanceOf(expectedClass: Class<*>) = expectedClass.isInstance(this)

Cheers.


#3

Thanks. I was somehow trapped in using is like this: object is expetedClass, but that didn’t work.