Skip to content

Instantly share code, notes, and snippets.

@JH108
Last active June 17, 2022 15:59
Show Gist options
  • Save JH108/cea5f78df41a72910adc9bc53115f961 to your computer and use it in GitHub Desktop.
Save JH108/cea5f78df41a72910adc9bc53115f961 to your computer and use it in GitHub Desktop.
Exploring the plus and minus operators for immutable lists in Kotlin
// TLDR: If you use list - [element] then it will remove the first occurrance of that element.
// If you use list - listOf([element]) then it will remove all occrrances of that element.
// If you use list + [element] then it will append regardless if that element already matches one in the list.
fun main() {
var t = listOf<Boolean>()
t = t + true
println("t + true: $t") // t + true: [true]
t = t + false
println("t + false: $t") // t + false: [true, false]
t = t + false
println("t + false: $t") // t + false: [true, false, false]
t = t + true
println("t + true: $t") // t + true: [true, false, false, true]
t = t + false
println("t + false: $t") // t + false: [true, false, false, true, false]
t = t - false
println("t - false: $t") // t - false: [true, false, true, false]
t = t - true
println("t - true: $t") // t - true: [false, true, false]
t = t + true
println("t + true: $t") // t + true: [false, true, false, true]
t = t + false
println("t + false: $t") // t + false: [false, true, false, true, false]
t = t - listOf(true)
println("t - listOf(true): $t") // t - listOf(true): [false, false, false]
t = t - listOf(false)
println("t - listOf(false): $t") // t - listOf(false): []
}
/* Full Output
t + true: [true]
t + false: [true, false]
t + false: [true, false, false]
t + true: [true, false, false, true]
t + false: [true, false, false, true, false]
t - false: [true, false, true, false]
t - true: [false, true, false]
t + true: [false, true, false, true]
t + false: [false, true, false, true, false]
t - listOf(true): [false, false, false]
t - listOf(false): []
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment