You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Kotlin的when匹配两个密封类并获取内部值?

Kotlin中Pair的类型匹配为何无法编译?

首先看示例代码:

sealed class Person {
    data class A(val i: Int) :
        Person()
}

fun main() {
    val a = Person.A(i = 0)
    val b = Person.A(i = 1)
    
    // 可正常编译
    when (a) { 
        is Person.A -> print("I have access to {$a.i}")
    }
    
    // 无法编译 :(
    when (a to b) { 
        is Person.A to is Person.A -> print("I have access to {$a.i} and b {$b.i}")
    }
}

编译报错信息(翻译后):

不兼容的类型: Person.A 和 Pair<Person.A, Person.A>
期待 '>'
期待一个元素
不兼容的类型: Person.A 和 Pair<Person.A, Person.A>

原因解析

你写的is Person.A to is Person.A是非法语法:

  • Kotlin的is类型检查只能直接作用于单个变量,不能用to将两个is检查拼接起来。
  • 编译器会错误地将这个表达式理解为试图创建一个Pair,但is Person.A本身不是合法的表达式(它是类型检查操作,不是值),同时最终生成的类型和a to b的Pair<Person, Person>完全不兼容,导致编译失败。

解决方案

如果要同时匹配两个变量的类型并访问内部属性,有几种可行的写法:

1. 解构Pair后用逻辑与判断

val (first, second) = a to b
when {
    first is Person.A && second is Person.A -> print("I have access to ${first.i} and ${second.i}")
}

2. 直接匹配Pair的具体类型

利用Kotlin的智能转换,匹配Pair<Person.A, Person.A>后直接访问属性:

when (a to b) {
    is Pair<Person.A, Person.A> -> print("I have access to ${a.i} and ${b.i}")
}

3. 嵌套when(更贴合密封类的匹配风格)

when (a) {
    is Person.A -> when (b) {
        is Person.A -> print("I have access to ${a.i} and ${b.i}")
    }
}

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:57:30