# Casting operator "as" as a method with type checking

**URL:** <https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705>\
**Category:** Language Design\
**Created:** [November 26, 2023, 11:16am UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705 "2023-11-26T11:16:16Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![tomerarazy](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/tomerarazy/32/10594_2.png) [@tomerarazy](https://discuss.kotlinlang.org/u/tomerarazy)\
**Post date:** [November 26, 2023, 11:16am UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705/1 "2023-11-26T11:16:16Z")

</div>

I don’t really like the syntax of casting in Kotlin since it doesn’t play nice with chaining methods or require me with use “let”

```auto
someClass.getObject().let {it as SomeObject }

```

So I’ve created a method to replace this:

```auto
inline fun <reified V : Any> Any.asOrFail(): V = this as V

```

So now the code look something like that:

```auto
someClass.getObject().asOrFail<SomeObject>()

```

But the problem is that this function doesn’t respect type boundary since it has no information on the type of “this”.  
I was trying to do something like this instead:

```auto
inline fun <T : Any, reified V : Any> T.asOrFail(): V = this as V

```

But the problem is that now I have to specify both types when calling the method which is really verbose since the “this” type is already known to the compiler:

```auto
someClass.getObject().asOrFail<BaseObject, SomeObject>()

```

Is there any alternative to this?

---

<div class="post-metadata">

**Author:** ![gidds](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/gidds/32/10865_2.png) [@gidds](https://discuss.kotlinlang.org/u/gidds)\
**Post date:** [November 26, 2023, 7:11pm UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705/2 "2023-11-26T19:11:38Z")

</div>

Can you expand on what you mean by “doesn’t respect type boundary”?

---

<div class="post-metadata">

**Author:** ![sylvainspinelli](https://avatars.discourse-cdn.com/v4/letter/s/0ea827/32.png) [@sylvainspinelli](https://discuss.kotlinlang.org/u/sylvainspinelli)\
**Post date:** [November 26, 2023, 8:32pm UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705/3 "2023-11-26T20:32:00Z")

</div>

For me this `fun` works:

```kotlin
inline fun <reified T> Any.asOrFail(): T = this as T

fun main() {
	val x= ""
	println(x.asOrFail<Int>().dec())
}

```

=\>

```auto
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
	at TestKt.main(test.kt:10)
	at TestKt.main(test.kt)

```

And:

```kotlin
fun main() {
	val x= 12
	println(x.asOrFail<Int>().dec())
}

```

=\>

```auto
11

```

So I don’t understand your problem!

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [November 26, 2023, 10:25pm UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705/4 "2023-11-26T22:25:16Z")

</div>

I guess OP meant to allow casting to subtypes only, so this doesn’t compile: `"hello".asOrFail<Int>()`. Nice to have, although even the `as` operator doesn’t do this. It only generates a warning that the code always fails.

---

<div class="post-metadata">

**Author:** ![tomerarazy](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/tomerarazy/32/10594_2.png) [@tomerarazy](https://discuss.kotlinlang.org/u/tomerarazy)\
**Post date:** [November 27, 2023, 8:25am UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705/5 "2023-11-27T08:25:06Z")

</div>

Just to specify exactly what I mean, If I have 2 unrelated classes (hierarchy wise): `A` and B and I try to case A to B:

```auto
class A
class B
fun castToA(a: A) = a as? B

```

I’ll get a compiler warning that the result of this cast is always null.  
If I use my `asOrFail` method I don’t get this warning which makes this version unsafe.

I also tried this version:

```auto
inline fun <T: Any, reified V : T> T.asOrNull(c: Class<V>): V? = this as? V

```

But for some reason I can pass whatever class I want as an argument even if V doesn’t extends T

---

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [November 27, 2023, 8:38am UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705/6 "2023-11-27T08:38:47Z")

</div>

> [@tomerarazy](#):
>
> But for some reason I can pass whatever class I want as an argument even if V doesn’t extends T

This is because `T` is inferred to `Any` in order to allow `V` to subtype it. This is just how generic functions work - they always try to infer types that will meet all requirements.

Kotlin has an internal feature which allows to “lock” parameter types to exactly provided types. We need to annotate the type with `@kotlin.internal.Exact` which is, well, internal:

```kotlin
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
inline fun <T: Any, reified V : T> @kotlin.internal.Exact T.asOrNull(c: Class<V>): V? = this as? V

```

Of course, do it at your own risk, it may stop working in future versions of Kotlin.

---

<div class="post-metadata">

**Author:** ![tomerarazy](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/tomerarazy/32/10594_2.png) [@tomerarazy](https://discuss.kotlinlang.org/u/tomerarazy)\
**Post date:** [November 27, 2023, 9:58am UTC](https://discuss.kotlinlang.org/t/casting-operator-as-as-a-method-with-type-checking/27705/7 "2023-11-27T09:58:01Z")

</div>

Thanks @broot ! That’s what I was looking for, just wish it was with a nicer syntax (without the need to pass an argument).  
Do you know why is `@kotlin.internal.Exact` is internal? seems quite useful for some cases.
