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

Steven Wang

09/12/2020, 5:24 PM
val actuallObj: List<*> = listOf("a", "b")
how to get the contained object type (String here) ?
n

nanodeath

09/12/2020, 5:37 PM
Java has type erasure, so you can't actually do that
n

nfrankel

09/12/2020, 5:45 PM
i’m not sure i understand your question as @nanodeath wrote, it’s not possible to get the type at runtime because of type erasure otherwise, it’s inferred at compile-time by the kotlin compiler
val actuallObj = listOf("a", "b")
actually, the type is
List<String>
val actuallObj: List<String> = listOf("a", "b")
actually, you’re actually removing type information with your syntax 😅
👆 1
m

Matteo Mirk

09/14/2020, 4:00 PM
You can’t for the list as a whole, but with reflection you can actually retrieve the runtime type of each element.
s

Steven Wang

09/14/2020, 4:56 PM
Thanks for helping out guys!! yes, I end up just check first element in my list as I knew I added them with same type. That worked out for me
n

nanodeath

09/14/2020, 4:58 PM
if that works, great 👍 watch out for polymorphic types
m

Matteo Mirk

09/15/2020, 8:07 AM
@Steven Wang Just out of curiosity: if you have all elements of the same type, why can’t you declare the list with a bounded type parameter? Like
List<String>
?
s

Steven Wang

09/15/2020, 10:13 AM
I was using krangl, one of the column I put in data with type
LocalDateTime
krangl dataframe will assign it as
AnyCol
, it will be convenient to know which column is
LocaldateTime
which I can convert to
ZonedDateTime
and plot as x-axis
m

Matteo Mirk

09/15/2020, 11:16 AM
Oh I see, you’re constrained by a library. Thanks for explaining
2 Views