I try to create a function to identify data types ...
# getting-started
k
I try to create a function to identify data types
Copy code
fun <T> checkType(args: T): String {
    return when(args) {
        Int -> "Yes! it's Integer"
        String -> "Yes! it's String"
        Boolean -> "Yes! it's Boolean"
        Double -> "Yes! it's Double"
        listOf<Any>() -> "Yes! it's List"
        mapOf<Any, Any>() -> "Yes! it's Map"
        else -> "Can't identify"
    }
}
But, when I call this function like
checkType("I have 3 cats")
the output always display
"Can't identify"
. What's wrong with my logic? Thanks in advance
solved 2
d
String
->
is String
s
You need to use
is
to perform a type check. What you're doing here is actually checking for equality.
The only reason this compiles at all is because
String
ends up referring to the companion object of the String class. It checks whether
args
is equal to
String.Companion
😞
By the way,
listOf<Any>()
will also end up doing an equality check, so it will only match against empty lists. Same logic applies; you would need
is List<*>
to match all lists.
j
you already have
typeOf<SomeType>()
s
Another note: the generic type argument isn't serving any purpose in your example. Just use
fun checkType(args: Any)
.
s
☝️
typeOf
could help if the type is known at compile time, but not if you need to figure out the type of some unknown object at runtime. Depends on the use case, but this scenario seems more like the latter.
j
Are you sure about that? I think it should work in runtime too
s
It uses a reified type parameter, which means the type is actually inferred at compile time. If you were to try and write something like
Copy code
fun <T> checkType(args: T) = typeOf<T>()
you'd just get a compile-time error saying "can't use T as a reified type parameter"
k
Thanks for all of the replies. I've seen the code run correctly except on
mapOf<Any, Any>()
I've tried to change
Any
with
*
but it return an error
s
Same as the
List
one, you need to use
is Map<*, *>
k
Ok, thank you all
Sorry for this stupid question. I'm a beginner
m
No question is stupid
💯 3