6

I try to use Java 12 in IntelliJ but when I try to run My app occurs error

Error:(57, 32) java: switch expressions are a preview feature and are disabled by default.
  (use --enable-preview to enable switch expressions)

I added in app configuration VM option --enable-preview but this error still occurs. I added SDK paths. Anyone have idea what I do wrong?

List<Car> sortedCars = switch (sortType) {
    case COLOR -> cars.stream().sorted(Comparator.comparing(Car::getColor)).collect(Collectors.toList());
    case MILEAGE -> cars.stream().sorted(Comparator.comparing(Car::getMileage)).collect(Collectors.toList());
    case MODEL -> cars.stream().sorted(Comparator.comparing(Car::getModel)).collect(Collectors.toList());
    case PRICE -> cars.stream().sorted(Comparator.comparing(Car::getPrice)).collect(Collectors.toList());
};
Vipin
  • 4,851
  • 3
  • 35
  • 65
Mateusz Sobczak
  • 1,551
  • 8
  • 33
  • 67
  • which intellij version? – Sebastian S Apr 28 '19 at 08:34
  • @SebastianS IDEA 2019.1.1 – Mateusz Sobczak Apr 28 '19 at 08:36
  • 2
    As a side note, try to avoid code duplication, as otherwise, you are ignoring the actual benefit of switch expressions. Consider `List sortedCars = cars.stream().sorted( switch (sortType) { case COLOR -> Comparator.comparing(Car::getColor); case MILEAGE -> Comparator.comparing(Car::getMileage); case MODEL -> Comparator.comparing(Car::getModel); case PRICE -> Comparator.comparing(Car::getPrice); } ).collect(Collectors.toList());` – Holger Apr 29 '19 at 13:07
  • 1
    Avoid duplication even further: `List sortedCars = cars.stream().sorted(Comparator.comparing(switch (sortType) { case COLOR -> Car::getColor; case MILEAGE -> Car::getMileage; case MODEL -> Car::getModel; case PRICE -> Car::getPrice; } ).collect(Collectors.toList());` – Advicer Nov 27 '19 at 10:31

2 Answers2

6

By default the Language Level is set to "12 - No new language feature". You need to change it to "12 (Preview) - Switch Expression" and you will get a popup to accept the Preview changes. Post which you will be able to run switch expressions in intellij.

Language Levels Settings

JDK 12 Preview

I am using IntelliJ IDEA 2019.1.1 (Community Edition)

Sachin
  • 2,087
  • 16
  • 22
4

Please make sure that the "Project language level" setting in the Project Structure dialog for your project is set to Java 12. In this case, IntelliJ IDEA will add the --enable-preview option automatically.

The VM options field in the run configuration affects how your application is launched, not how it's compiled, so adding that option there has no effect.

yole
  • 92,896
  • 20
  • 260
  • 197