Kiki Abdullah
02/18/2022, 9:11 AMfun <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 advanceDominaezzz
02/18/2022, 9:16 AMString
-> is String
Sam
02/18/2022, 9:16 AMis
to perform a type check. What you're doing here is actually checking for equality.Sam
02/18/2022, 9:18 AMString
ends up referring to the companion object of the String class. It checks whether args
is equal to String.Companion
😞Sam
02/18/2022, 9:18 AMlistOf<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.Javier
02/18/2022, 9:20 AMtypeOf<SomeType>()
Sam
02/18/2022, 9:20 AMfun checkType(args: Any)
.Javier
02/18/2022, 9:21 AMSam
02/18/2022, 9:23 AMtypeOf
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.Javier
02/18/2022, 9:25 AMSam
02/18/2022, 9:27 AMfun <T> checkType(args: T) = typeOf<T>()
you'd just get a compile-time error saying "can't use T as a reified type parameter"Kiki Abdullah
02/18/2022, 9:30 AMmapOf<Any, Any>()
I've tried to change Any
with *
but it return an errorSam
02/18/2022, 9:31 AMList
one, you need to use is Map<*, *>
Kiki Abdullah
02/18/2022, 9:36 AMKiki Abdullah
02/18/2022, 9:36 AMMichael de Kaste
02/18/2022, 9:40 AM