Search code examples
androidkotlinkotlin-extension

How to keep object type for smart casting when returning Any


Apologies if this is a silly question, Kotlin is still new to me and I'm unfamiliar with syntax "types" so found it difficalt to find the solution.

fun Any?.test(): Any?
{
    return this
}

"test string".test() // implicit string is now type of "Any"
"test string".test().substring() // what i'm trying to achieve 

I basically want the class extension method to return its own instance so I can still operate on it as per the bottom line of the example

Excuse the crassness of the example, was simplified down


Solution

  • You can make your extension function generic, then it should work.

    fun <T> T?.test(): T?
    {
        return this
    }