I have generic type, checkType(10) and compiler say it's Integer

*My expectation
input: checkType(10)
output: “Yes! it’s Integer”

This is some mandatory value types.
• Integer
• String
• Boolean
• Double
• List
• Map<String, String>

fun <T> checkType(args: T): String {
   return ""
}

fun main() {
    println(
        """
        '[10, 9, 8 , 6]' is List? ${checkType(listOf(10, 9, 8, 6))}
        'Yeay' is String? ${checkType("Yeay")}
        'True' is Boolean? ${checkType(true)}
        '10.01' is List? ${checkType(10.01)}
    """.trimIndent()
    )
}

I’m not entirely sure what do you need. Something like this?

fun <T> checkType(args: T): String = when (args) {
    is Int -> "Yes! it’s Integer"
    ...
    else -> throw UnsupportedOperationException()
}
1 Like

My code like this, whether this best practice ?
Please review my code

fun <T> checkType(args: T): String {
    when(args){
        is Int-> return "Yes! it's Integer"
        is String-> return "Yes! it's String"
        is Boolean-> return "Yes! it's boolean"
        is Double-> return "Yes! it's Double"
        is List<*>-> return "Yes! it's List"
        is Map<*, *>-> return "Yes! it's Map"
    }
    return " "
}

Maybe something like this would be better:

import kotlin.reflect.*
private val acceptedTypes = listOf(Int::class, String::class, Boolean::class, Double::class, List::class, Map::class)
fun <T> checkType(args: T): String {
    return acceptedTypes.firstNotNullOfOrNull { if(it.isInstance(args)) "Yes! it's ${it.simpleName}" else null } ?: " "
}

fun main(){
    println(checkType(listOf(42)))
    println(checkType(42))
    println(checkType("hello world"))
}