Java 12 intellij开关表达式不起作用

问题描述 投票:4回答:2

我尝试在IntelliJ中使用Java 12,但是当我尝试运行我的应用程序时发生错误

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

我添加了应用程序配置VM选项--enable-preview但仍会出现此错误。我添加了SDK路径。谁知道我做错了什么?

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());
};
java intellij-idea switch-statement java-12 switch-expression
2个回答
4
投票

请确保项目的“项目结构”对话框中的“项目语言级别”设置设置为Java 12.在这种情况下,IntelliJ IDEA将自动添加--enable-preview选项。

运行配置中的VM选项字段会影响应用程序的启动方式,而不会影响其编译方式,因此添加该选项无效。


3
投票

默认情况下,语言级别设置为“12 - 无新语言功能”。您需要将其更改为“12(预览) - 切换表达式”,您将获得一个弹出窗口以接受预览更改。发布你可以在intellij中运行switch表达式。

语言级别设置

JDK 12 Preview

我正在使用IntelliJ IDEA 2019.1.1(社区版)

© www.soinside.com 2019 - 2024. All rights reserved.