Java Reference
In-Depth Information
javac: Incompatible Types
In the BackCmd plugin version where we're saving player locations to disk, I
made a typo: playerTeleports returns a Stack of Location objects. But I accidentally
tried to assign it to a stack of Player objects, like this:
Stack <Player> locs = playerTeleports.get(player.getName());
That results in the fairly straightforward error message “incompatible types”:
src/backcmdsave/ incompatible types
found : java.util.Stack<>
required: java.util.Stack<>
Stack <Player> locs = playerTeleports.get(player.getName());
Java says it found a Location where it was expecting me to use a Player . Of course
that's backwards—that's not what I meant at all.
At times like this it really helps to think like the computer does (in this case,
to think like the compiler does). So imagine you're the Java compiler. You
just completed reading a line of code through to the semicolon, and you're
starting the next line. You see this first part:
Stack <Player> locs =
Ah! The programmer is declaring a variable named locs , and it's a generic Stack
of Player objects. And we're about to assign an initial value to it.
Then the compiler sees the next part of the statement:
You (the compiler) look up playerTeleports.get() and see that it returns a Stack of
Location objects. Well, that won't do at all. Here the programmer says we've got
a Stack of Player objects, and now the code is trying to assign a Stack of Location
objects. So from the point of view of the compiler, you expected a Player and
instead got a Location .
The compiler, of course, is wrong.
That's because no compiler can really infer your intent . The compiler can only
judge what you've actually done, not what you intended to do.
Always bear that in mind when trying to decipher compiler error messages:
they are from the compiler's point of view, and it cannot read your mind. At
least not yet. We're working on it.
At any rate, correcting the type of the Stack to match corrects the problem:
Stack <Location> locs = playerTeleports.get(player.getName());
Search WWH ::

Custom Search