You need to enable JavaScript to run this app. Intellij IDEA 2020.3.3中Java16使用Switch模式匹配报Expression expected
优惠活动
大模型
产品
解决方案
定价
更多

Intellij IDEA 2020.3.3中Java16使用Switch模式匹配报Expression expected

报错原因与修复方案

1. 触发「Expression expected」的直接原因

  • 你在switch分支中写了r.、v.、sv. 这种只有变量名加末尾空点的无效代码,编译器在点号后找不到合法表达式,直接抛出该报错。
  • 结合业务逻辑,此处需要调用各Client实现的currentLimit()方法获取额度,补全方法调用即可修复:
    public Result add(LineItem lineItem) {
        return switch (client) {
            case Regular r -> addAnItemIfTheLimitIsNotExceeded(r.currentLimit());
            case Vip v -> addAnItemIfTheLimitIsNotExceeded(v.currentLimit());
            case SuperVip sv -> addAnItemIfTheLimitIsNotExceeded(sv.currentLimit());
        };
    }
    

2. 其他语法问题

  • 类声明错误:public class Order() { 混淆了普通类与Record的声明规则,普通类的类名后不能带空括号,需去掉括号修正:
    // 错误写法
    public class Order() { ... }
    // 正确写法
    public class Order { ... }
    

3. Java 16的特性适配问题

Java 16的正式支持特性存在范围限制:

  • Java 16仅稳定支持Records、密封接口/类特性,你使用的带类型绑定变量的switch模式匹配(即case Regular r ->这类分支写法)是Java 17才进入预览、后续版本正式落地的能力,Java 16本身不支持这类语法。
  • 如果坚持使用Java 16,可替换为Java 16支持的instanceof模式匹配写法(需已开启对应预览特性):
    public Result add(LineItem lineItem) {
        Limit limit;
        if (client instanceof Regular regular) {
            limit = regular.currentLimit();
        } else if (client instanceof Vip vip) {
            limit = vip.currentLimit();
        } else if (client instanceof SuperVip superVip) {
            limit = superVip.currentLimit();
        } else {
            // 密封接口已枚举所有允许的实现类型,该分支不会触发
            throw new IllegalStateException("Unexpected client type");
        }
        return addAnItemIfTheLimitIsNotExceeded(limit);
    }
    
  • 如果需要使用模式匹配的switch语法,建议升级到Java 17及以上LTS版本,开启对应预览特性即可正常运行。

注:由于Client是密封接口,编译器会自动校验所有实现类型的分支覆盖度,不需要额外添加默认分支。

内容的提问来源于stack exchange,提问作者K2mil J33

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 12:27:02