How to write an isInstanceOf method?


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?


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>) {

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)



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