Tag: 模式匹配

Kotlin中元组的模式匹配

我有以下一段代码 fun changeSelection(item: FileOrFolder, selected: Boolean) { selection = when(item) { is Folder -> { when(selected) { true -> selection + item false -> selection – item } } is File -> { when(selected) { true -> selection + item false -> selection – item } } else -> throw Exception("unreachable") } } 看起来有点凌乱,因为我习惯了scala的这个 def […]

Kotlin当()局部变量的引入

假设我有一个名为doHardThings()函数可能会返回各种不同的类型,我想根据返回的类型采取行动。 在Scala中,这是match构造的常见用法: def hardThings() = doHardThings() match { case a: OneResult => // Do stuff with a case b: OtherResult => // Do stuff with b } 我正在努力弄清楚如何在Kotlin中干净地完成这个工作,而不用为doHardThings()引入一个临时变量: fun hardThings() = when(doHardThings()) { is OneResult -> // Do stuff… with what? is OtherResult -> // Etc… } 什么是这种常见用例的惯用Kotlin模式?