Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 190

Returning Consistent Data Types

Оглавление

The first rule of using a switch expression is probably the easiest. You can't return incompatible or random data types. For example, can you see why three of the lines of the following code do not compile?

int measurement = 10; int size = switch(measurement) { case 5 -> 1; case 10 -> (short)2; default -> 5; case 20 -> "3"; // DOES NOT COMPILE case 40 -> 4L; // DOES NOT COMPILE case 50 -> null; // DOES NOT COMPILE };

Notice that the second case expression returns a short, but that can be implicitly cast to an int. In this manner, the values have to be consistent with size, but they do not all have to be the same data type. The last three case expressions do not compile because each returns a type that cannot be assigned to the int variable.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх