mg6maciej
04/24/2017, 12:15 PMpublic operator fun <T> Iterable<T>.minus(element: T): List<T>
be defined with element as nullable?
public operator fun <T> Iterable<T>.minus(element: T?): List<T>
I.e. if you call listOf<String>(...) - null as String?
it would just return the same List<String>
and not List<String?>
as it currently does.
8 replies
val list1: List<Int?> = arrayListOf(1, null).minusNullable(null)
println("list1: $list1")
val list2: List<Int> = arrayListOf(1, 2).minusNullable(null)
println("list2: $list2")
compiles and prints:
list1: [1]
list2: [1, 2]
where minusNullable
is a slightly changed minus
operator (essentially argument type changed to T?
):
fun <T> Iterable<T>.minusNullable(element: T?): List<T> {
val result = ArrayList<T>()
var removed = false
return this.filterTo(result) { if (!removed && it == element) { removed = true; false } else true }
}