Follow

Every, single, damn, time.

class <T extends SomeClass> TheClass implements Iterable<T> {...}

I call something with a raw TheClass return type (not my API), and I get confused why this doesn't work:

for(SomeClass thingy : instanceOfTheClass) { ... }

The raw type doesn't have a generic type at all, so it doesn't have a upper bound like let's say SomeClass. So the enhanced for loop sees an Iterable dishing out Object instances, not SomeClass instances.

I fall for it. Every, single, damn, time.

@dammkewl is it C++? I would suggest you Scala where we have both higher/lower bound type generics :) docs.scala-lang.org/tour/upper

@ott0disk It's Java actually. There are lower and higher bound type generics there. And that's actually the case in my example.

What's happening is that the class should be handled as a generically typed class so that the compiler can make use of the boundary declared in the class.

But I encounter a raw type of it instead and so the bounds magically disappear entirely.

I don't know Scala, but if it has raw types, I expect it to have similar issues (specially since its both on the same JVM).

@dammkewl Oh yes actually it's called type erasure in Scala but i guess it's the same as Java's "raw types". However the scala compiler does throw a warning when it foresees this situation, also there is a workaround of having a "TypeTag" in scope (basically reflection).

Sign in to participate in the conversation
Bitcoin Mastodon

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!