nerses
05/06/2025, 11:41 PMopen class Parent(
open val numbers: List<Int>
) {
val sortedNumbers: List<Int> = numbers.sorted()
}
class Child(
override val numbers: List<Int>
): Parent(numbers)
fun main() {
println(Child(emptyList()).sortedNumbers)
}
it fails with
Exception in thread "main" java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.collections.CollectionsKt___CollectionsKt.sorted, parameter <this>
at kotlin.collections.CollectionsKt___CollectionsKt.sorted(_Collections.kt)
at Parent.<init>(Blah.kt:4)
at Child.<init>(Blah.kt:9)
at BlahKt.main(Blah.kt:12)
at BlahKt.main(Blah.kt)
ephemient
05/07/2025, 1:15 AMephemient
05/07/2025, 1:18 AMpublic class Parent {
private List<Int> numbers;
private List<Int> sortedNumbers;
public Parent(List<Int> numbers) {
this.numbers = numbers;
sortedNumbers = getNumbers().sorted();
}
public List<Int> getNumbers() {
return numbers;
}
public final List<Int> getSortedNumbers() {
return sortedNumbers;
}
}
public final class Child extends Parent {
private List<Int> numbers;
public Child(List<Int> numbers) {
super(numbers);
this.numbers = numbers;
}
@Override
public List<Int> getNumbers() {
return numbers;
}
}
ephemient
05/07/2025, 1:19 AMParent
uses the overridable getNumbers
, and at that point during construction, the backing field Child.numbers
is still null
ephemient
05/07/2025, 1:19 AMopen val
with a backing field is almost always a mistakeephemient
05/07/2025, 1:20 AMephemient
05/07/2025, 1:21 AM