Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room Entity boolean with DAO: Kotlin vs Java

I'm attempting to migrate some of my Android Java POJO classes to Kotlin. Some of these classes are used in as a Room Entity.

According to the documentation for Defining data using Room entities, getters and setters are to be named in JavaBean convention.

If you use getter and setter methods, keep in mind that they're based on JavaBeans conventions in Room.

With JavaBeans and a boolean field, it should be like this in Java

@Entity
public class MyObject {
    // other stuff
    public MyObject() {
        this.enabled = false;
    }

    public boolean isEnabled() { return this.enabled; }
    public void setEnabled(boolean enabled) { this.enabled = enabled; }
}

Now within a DAO, this can be referenced as such with enabled = 1

@Query("select * from myobject where enabled = 1")
public List<MyObject> loadEnabledObjects();

In Kotlin the object reduces to this

@Entity
class MyObject {
    // other stuff
    var isEnabled: Boolean = false
}

When using a DAO as before, there is a compile time error

error: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such column: enabled)

This appear to be that the Room entity is behaving different in my Kotlin version and to reference the Kotlin version with DAO, I must change the query to use isEnabled = 1

@Query("select * from myobject where isEnabled = 1")
public List<MyObject> loadEnabledObjects();

There aren't any official Kotlin examples on Defining data using Room entities, and I want to make sure this is the correct behavior before I change all of my DAOs.

Is this correct, or am I missing something with the Kotlin Entity such an annotations or a different naming scheme?

like image 281
Kirk Avatar asked Jul 13 '26 10:07

Kirk


1 Answers

After inspecting the generated Bytecode, this Kotlin code

var isEnabled: Boolean

Creates the following methods

public Boolean isEnabled();
public void setEnabled();

In order to do this in Kotlin and use them in a DAO while keeping JavaBean convention, the query needs to use isEnabled

@Query("select * from myobject where isEnabled = 1")
public List<MyObject> loadEnabledObjects();

I'm still unsure why a DAO won't work with the same query syntax under Kotlin as under Java since they both have the same methods and signatures. Since my code all relies on the JavaBean convention I've just altered the queries.


Just for added notes I came across inspecting the generated bytecode, this Kotlin code

var enabled: Boolean

Generates these methods

public Boolean getEnabled();
public void setEnabled();
like image 87
Kirk Avatar answered Jul 16 '26 00:07

Kirk