Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on tuples in Kotlin

I have the following piece of code

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")
    }
}

which looks kinda cluttered for me as I got used to this in 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
    }
}

Is there a way to achieve something similar in Kotlin?

like image 581
Yaroslav Avatar asked Sep 23 '15 16:09

Yaroslav


1 Answers

Well, for Scala's sake, you can write:

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()
    }
}

A more straight-forward version would be:

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()
        }
}

But I definitely prefer:

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
}
like image 145
voddan Avatar answered Sep 21 '22 08:09

voddan