Kotlin中元组的模式匹配

时间:2015-09-23 16:42:29

标签: pattern-matching tuples 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 changeSelection(item: FileOrFolder, selected: Boolean) {
    (item, selected) match {
        case (item: Folder, true) => selection + item
        case (item: Folder, false) => selection - item
        case (item: File, true) => selection + item
        case (item: File, false) => selection - item
    }
}

有没有办法在Kotlin中实现类似的东西?

1 个答案:

答案 0 :(得分:13)

好吧,为了Scala的缘故,你可以写:

fun changeSelection(item: FileOrFolder, selected: Boolean) {
    selection = when {
        item is Folder &&  selected -> selection + item
        item is Folder && !selected -> selection - item
        item is File   &&  selected -> selection + item
        item is File   && !selected -> selection - item
        else -> throw Exception()
    }
}

更直接的版本是:

fun changeSelection(item: FileOrFolder, selected: Boolean) {
    selection = if(selected)
        when(item) {
            is Folder -> selection + item
            is File   -> selection + item
            else -> throw Exception()
        }
    else
        when(item) {
            is Folder -> selection - item
            is File   -> selection - item
            else -> throw Exception()
        }
}

但我绝对更喜欢:

operator fun Selection.plus(f: FileOrFolder) = ...
operator fun Selection.minus(f: FileOrFolder) = ...

fun changeSelection(item: FileOrFolder, selected: Boolean) {
    if(selected)
        selection += item
    else 
        selection -= item
}