ScruffyFox
ScruffyFox

Reputation: 160

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

Upvotes: 0

Views: 98

Answers (2)

rozina
rozina

Reputation: 4232

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

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

Upvotes: 1

zsmb13
zsmb13

Reputation: 89548

You can use a generic function:

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

Upvotes: 5

Related Questions