Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 12 intellij switch expressions doesn't work

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());
};
like image 540
Mateusz Sobczak Avatar asked Jan 01 '23 01:01

Mateusz Sobczak


2 Answers

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)

like image 175
Sachin Avatar answered Jan 04 '23 17:01

Sachin


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.

like image 37
yole Avatar answered Jan 04 '23 17:01

yole