Dont know which channel to ask this in to be hones...
# getting-started
j
Dont know which channel to ask this in to be honest. I want to know why I cant do if (foobar is List<MyType>) and enforce me to using List<*> instead. I want typesafety for which items types to be allowed combined with List. Is it possible do this somehow?
j
Yeah but why cant I do it, I mean why does type-erasure exists? I do understand its generics and such, but wonder both why it has its limitation and how do I solve it or work around it.
Like in my case I have a Map<String, Any> where I want to make sure Any is of type List<A> and not List<Any> ๐Ÿ™‚
I guess I am enforced doing like Map<String, SealedInterfaceA> where SealedInterfaceA includes a variant of sent in List<A>? Or is there any other solution?
v
Why it is done, you have to ask the language designers. Maybe because of having JVM class files as first compilation target where types are also erased. Maybe because it would be too much overhead to check it at runtime. No idea. You cannot really work-around it unless you have reified types, as the information is just not present at runtime.
Maybe if you create a
MyTypeList
class? ๐Ÿคทโ€โ™‚๏ธ
j
You mean like typealias MyTypeList = List<A>? ๐Ÿ™‚
v
No, an alias is just an alias
After compilation it would be the same
j
Ah ok, yeah seems like I need to refactor my code to avoid this, make each value in Map being more type safe and not using Any ๐Ÿ™‚
๐Ÿ‘Œ 1
k
If your lists are small (e.g. less than 10 items each) then you might find that the performance is acceptable if you do
if (foo is List<*> && foo.all { it is A })
. But refactoring your code to avoid this would be better.
j
@Klitos Kyriacou Thanks didnt thought about that solution ๐Ÿ˜„ I have refactored my code to avoid this state to begin with. Having a quite complex over generic multi select component with List types supporting anything, but fulfill an interface, but also using same object for all my question related components, like dropdown vs radiobuttons to give some context ๐Ÿ™‚
a
Type erasure exists because Java decided to maintain the compatibility with older code and programs when generics were introduced in Java 5. See this answer. In contrary, .NET framework introduced actual generics without type erasure in 2.0 but itโ€™s not compatible with code written for 1.1.
plus1 1
r
Both erasure and reification have their strengths and weaknesses, and neither is inherently better than the other. @cedric did a blog post on it a few years back that is worth a read: https://www.beust.com/weblog/erasure-vs-reification/
โž• 3
c
Wow 2011... yikes ๐Ÿ™‚
๐Ÿ˜† 1