Strange error "Val cannot be reassigned" when setting a property in Kotlin Java object

It is strange that my Kotlin code compiled earlier when it looked like this in the java class Allocator:

public void setAllocMethod(@NotNull AllocMethod allocMethod) {
    this.allocMethod = allocMethod;
}

but when I changed the setting of the Java class to this:

public void setAllocMethod(@Nullable AllocMethod allocMethod) {
    this.allocMethod= allocMethod;
}

then when I compile the project, I get this Kotlin error in the kt file that calls the java object:

Val cannot be reassigned

allocator.allocMethod = DefaultAllocMethod() // kotlin code

also here is java getter:

public @NotNull AllocMethod getAllocMethod() {
        if (allocMethod == null) allocMethod = DefaultAllocMethod.newDefault();
        return allocMethod;
}

DefaultAllocMethod is a subclass of java AllocMethod

Allocatorhas a type Allocatorthat is a java class that has a getter and setter described above.

Can someone explain what is happening? thank

+4
source share
2 answers

@Nullable AllocMethod, Kotlin AllocMethod?, getters @NotNull AllocMethod, Kotlin AllocMethod

, , getter . , var allocMethod val allocMethod fun setAllocMethod(...)

+6

, AllocMethod? Any? AllocMethod Any. , .

0

Source: https://habr.com/ru/post/1661305/


All Articles