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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With