Re: I don't understand enums



ptomblin+netnews@xxxxxxxxx (Paul Tomblin) writes:


public static final int PLAYLISTTYPE_FEATURE = PlaylistType.FEATURE.getID();
....
Note that they're still "public static final".

But now case statements that worked before the change are breaking with
Eclipse complaining that "case expressions must be constant expressions".
Huh? They sure look constant to me.

They are not "constant expressions" in the sense of the Java specification,
which means *compile time* constants. What you have is a method call, on
an object from another class. There is no way to know what that might
return when it's executed (remember, you might recompile PlaylistType
and not Playlist, and it should still work).

How could it think that
PLAYLISTTYPE_FEATURE could change values when it's declared final?

It's not that it can't change during one execution of the program,
but that it's no a compile time constant that can be inlined in the
switch statement implementation.

However, you can switch on enums too, so change the switch to do
switch (playlistType) {
case PlaylistType.FEATURE: // ...
case PlaylistType.TRAILER: // ...
}

(The compiler will, internally, assign a compile time constant to each
enum value and do the switch on that instead.)

/L
--
Lasse Reichstein Nielsen - lrn@xxxxxxxxxx
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
.



Relevant Pages

  • Re: case labels
    ... The language requires case labels to be compile time constants. ... The code generated for a switch statement is typically a static ... Please apply that thought to 'general integer expressions'. ...
    (comp.lang.c)
  • Re: In-Out Parameters for functions
    ... expressions with two or more impure function calls would need to switch ... your compiler vendor to put in a switch--the result of turning on the ... switch would still be a legal implementation of Ada. ...
    (comp.lang.ada)
  • RE: How "large" can a IIf be in a query?
    ... "Mattias" wrote: ... >> Switch is kind of similar to a multipart iif(). ... >> expressions, and associated values. ...
    (microsoft.public.access.queries)
  • Re: attn: regex gurus. can this be done with a regular expression or using a different technique?
    ... Larry, ... Microsoft decided to switch the capture ... So the final expressions that worked are: ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: case labels
    ... life problems the enhanced switch would have trouble with. ... He or she asked why general int expressions weren't allowed. ... What does strcmp() do if one of the parameters is NULL? ... I wasn't suggesting originally that C should be changed. ...
    (comp.lang.c)

Loading