Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

The strange thing is that my Kotlin code compiled fine before, when it looked like this in the java class Allocator:

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

but when I changed the java class' setter 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 the java getter:

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

DefaultAllocMethod is a java subclass of AllocMethod

allocator is of type Allocator, which is a java class that has the getter and setter described above.

Can anyone explain what is happening? thanks

like image 987
ycomp Avatar asked Nov 19 '16 18:11

ycomp


1 Answers

Your setters's type @Nullable AllocMethod, which is Kotlin's AllocMethod?, does not match the getters type @NotNull AllocMethod, which is Kotlin's AllocMethod

What the error message means is that since the types do not match, only the getter is considered as a property. So from the Kotlin's point of view instead of a var allocMethod you have val allocMethod and fun setAllocMethod(...)

like image 200
voddan Avatar answered Oct 12 '22 01:10

voddan