Reputation: 13
I have wrote a function getResult()
that has only one parameter.
If the attached argument is of type Int
, then the value returned is the value of the argument multiplied by 5.
If the attached argument is of type String
, the value returned is a character length.
If the attached argument is of type other than Int
and String
, then the returned value is 0.
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
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