Koh Endru
Koh Endru

Reputation: 13

how to check if argument is a string or int

I have wrote a function getResult() that has only one parameter.

How can I write getResult() so it returns 6?

fun main() {
    val stringResult = getResult("Kotlin")
    val intResult = getResult(100)

    println(stringResult)
    println(intResult)
}

fun <T> getResult(args: T) {
    // ???
}

Upvotes: 0

Views: 889

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8422

You can write something like this:

fun getResult(args: Any?): Int =
    when (args) {
        is Int -> args * 5
        is String -> args.length
        else -> 0
    }

Upvotes: 3

Related Questions