https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Kiki Abdullah

02/18/2022, 9:11 AM
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

Dominaezzz

02/18/2022, 9:16 AM
String
->
is String
s

Sam

02/18/2022, 9:16 AM
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

Javier

02/18/2022, 9:20 AM
you already have
typeOf<SomeType>()
s

Sam

02/18/2022, 9:20 AM
Another note: the generic type argument isn't serving any purpose in your example. Just use
fun checkType(args: Any)
.
s

Sam

02/18/2022, 9:23 AM
☝️
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

Javier

02/18/2022, 9:25 AM
Are you sure about that? I think it should work in runtime too
s

Sam

02/18/2022, 9:27 AM
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

Kiki Abdullah

02/18/2022, 9:30 AM
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

Sam

02/18/2022, 9:31 AM
Same as the
List
one, you need to use
is Map<*, *>
k

Kiki Abdullah

02/18/2022, 9:36 AM
Ok, thank you all
Sorry for this stupid question. I'm a beginner
m

Michael de Kaste

02/18/2022, 9:40 AM
No question is stupid
💯 3
18 Views