# How to write an isInstanceOf method?

**URL:** <https://discuss.kotlinlang.org/t/how-to-write-an-isinstanceof-method/2456>\
**Category:** Uncategorized\
**Created:** [March 31, 2017, 3:06pm UTC](https://discuss.kotlinlang.org/t/how-to-write-an-isinstanceof-method/2456 "2017-03-31T15:06:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![medium](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/medium/32/10404_2.png) [@medium](https://discuss.kotlinlang.org/u/medium)\
**Post date:** [March 31, 2017, 3:06pm UTC](https://discuss.kotlinlang.org/t/how-to-write-an-isinstanceof-method/2456/1 "2017-03-31T15:06:55Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![Shyish](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/shyish/32/2191_2.png) [@Shyish](https://discuss.kotlinlang.org/u/Shyish)\
**Post date:** [March 31, 2017, 4:39pm UTC](https://discuss.kotlinlang.org/t/how-to-write-an-isinstanceof-method/2456/2 "2017-03-31T16:39:10Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![medium](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/medium/32/10404_2.png) [@medium](https://discuss.kotlinlang.org/u/medium)\
**Post date:** [April 1, 2017, 6:40pm UTC](https://discuss.kotlinlang.org/t/how-to-write-an-isinstanceof-method/2456/3 "2017-04-01T18:40:32Z")

</div>

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