47

I agree that this code:

var y = switch (0) {
    case 0 -> '0';
    case 1 -> 0.0F;
    case 2 -> 2L;
    case 3 -> true;
    default -> 4;
};
System.out.println(y);
System.out.println(((Object) y).getClass().getName());

returns this:

0
java.lang.Character

But if you remove boolean:

var y = switch (0) {
    case 0 -> '0';
    case 1 -> 0.0F;
    case 2 -> 2L;
    default -> 4;
};
System.out.println(y);
System.out.println(((Object) y).getClass().getName());

returns this:

48.0
java.lang.Float

I suppose this result is unexpected.

Ilya
  • 720
  • 6
  • 14
  • Probably some kind of optimization. In the second example you can map all results to Float, in the first example they are just only Objects. – Ralf Renz Mar 22 '19 at 07:03
  • 14
    I would imagine it is for the same reason as `true ? '0' : false` would return a Character because it necessarily requires boxing, whereas `true ? '0' : 0.0f` would return a float because binary numeric promotion would occur. – Andy Turner Mar 22 '19 at 07:16
  • 3
    Can anybody point me to the bit of the language spec where they are defined. I can't find "switch expression" [mentioned](https://docs.oracle.com/javase/specs/jls/se12/html/index.html). – Andy Turner Mar 22 '19 at 07:28

1 Answers1

53

According to the switch expression's JEP 325, a switch expression is a poly expression:

A switch expression is a poly expression; if the target type is known, this type is pushed down into each arm. The type of a switch expression is its target type, if known; if not, a standalone type is computed by combining the types of each case arm.

Because you don't have a target type, the expression is not checked to match any given type, which is expected.

You can verify this by replacing var with a type:

int y = switch (0) {
    case 0 -> '0';
    case 1 -> 0.0F;
    case 2 -> 2L;
    case 3 -> true;
    default -> 4;
};

In my shell, this fails with:

|  Error:
|  incompatible types: bad type in switch expression
|      possible lossy conversion from float to int
|      case 1 -> 0.0F;
|                ^--^
|  Error:
|  incompatible types: bad type in switch expression
|      possible lossy conversion from long to int
|      case 2 -> 2L;
|                ^^
|  Error:
|  incompatible types: bad type in switch expression
|      boolean cannot be converted to int
|      case 3 -> true;
|                ^--^

But if you remove boolean:...

It should be enough to see how the standalone type is determined (rules here):

The type of a standalone switch expression is determined as follows:

  • If the result expressions all have the same type (which may be the null type), then that is the type of the switch expression.

  • Otherwise, if the type of each result expression is boolean or Boolean, an unboxing conversion (5.1.8) is applied to each result expression of type Boolean, and the switch expression has type boolean.

  • Otherwise, if the type of each result expression is convertible to a numeric type (5.1.8), the type of the switch expression is the result of numeric promotion (5.6) applied to the result expressions.

  • Otherwise, boxing conversion (5.1.7) is applied to each result expression that has a primitive type, after which the type of the switch expression is the result of applying capture conversion (5.1.10) to the least upper bound (4.10.4) of the types of the result expressions.

As far as I can see, when you remove the boolean expression, you're left with numeric expressions (char '0' (int 48) is promoted to float 48.0). See third bullet point above.

And as for why float is the result's type, see the Numeric Contexts section.

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • 9
    good answer. 1+, this indeed follows whatever the binary numeric promotion existed in the JLS until switch expressions were added. – Eugene Mar 22 '19 at 08:35
  • why the first output gives you `java.lang.Character ` class? because boolean is after a float class. why float is not casting? – Akash Shah Mar 22 '19 at 08:41
  • 6
    @AkashShah I believe it's because no type conversion occurs. I haven't verified this, but I think the [least upper bound](https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.10.4) for all these expression's types is `java.lang.Object`. So it boils down to something like `Object y = ...` and the actual type of the result ends up being printed (`java.lang.Character` being the boxed type of the matched case expression, which returns `'0'`) – ernest_k Mar 22 '19 at 08:46
  • @ernest_k RE: "Because you don't have a target type, the expression is not checked to match any given type, which is expected." The target type exists and the compiler knows it. I think the main problem in this syntax. This does not allow me to easily see the target type, for example, when reviewing a code. – Ilya Mar 22 '19 at 09:37
  • 1
    @Ilya It may be about how I word it. But I'm referring to the difference between a standalone and a poly expression in this case (what's the difference between the version using `var` and the one using `int`? that's what I'm talking about). You can get a better idea by reading through [Chapter 5: Conversions and Contexts](http://cr.openjdk.java.net/~gbierman/switch-expressions.html#jep325-5) – ernest_k Mar 22 '19 at 09:47
  • 8
    @Ilya no, when you use `var`, there is no target type. In that case, the right-hand side has to be treated as stand-alone expression (not poly expression), to determine the expression type, *then*, the variable will get the resulting type. [As said by Andy Turner](https://stackoverflow.com/questions/55294208/why-does-java-12-try-to-convert-the-result-of-a-switch-to-a-number#comment97317523_55294208), the behavior is consistent with previous Java versions. The takeaway is, when the type is not obvious, don’t use `var` to declare a variable. – Holger Mar 22 '19 at 10:38
  • @Holger Yes, the variable has a type, in the first example it is Object, in the second it is a primitive float. I do not like this syntax, because I do not see this type. – Ilya Mar 22 '19 at 11:14
  • 7
    @Ilya no, in the first example, the variable’s type is an intersection type of `Object`,`Serializable`, and `Comparable>`. If you want `Object` (which would be relevant if you want to assign another value at a later point), you have to declare it explicitly. Your question’s example is equivalent to `var y = x == 0? '0': x == 1? 0.0F: x == 2? 2L: x == 3? true: 4;`. As said, use `var` when the right-hand side is obvious only. No-one forces you to use it at other places. – Holger Mar 22 '19 at 11:51
  • 1
    If I may draw a conclusion: don't make the life of t̵h̵e̵ ̵c̵o̵m̵p̵i̵l̵e̵r̵ yourself too hard by using multiple types for the `case`s in combination with an unknown target type (e.g. by using `var`). – MC Emperor Jun 23 '21 at 12:35