Room return kotlin Tuples from query

Viewed 1156

I'm using room database, and I want to query table column as kotlin Tuple. Can anyone help me in same?

So I have a table named User which has multiple fields and Now I want to query 2 specific fields first_name and last_name and Kotlin Tuples(Pair)


@Entity(tableName = "user")
data class User(
   var id: String,
   var first_name: String,
   var last_name: String
   // some other fields
)

@Dao
interface UserDao {

   @Query("SELECT first_name as first, last_name as second FROM user WHERE id = :id")
   fun getUserName(id: String): Pair<String, String>
}


I'm getting a compiler error like below:

Not sure how to convert a Cursor to this method's return type (kotlin.Pair<java.lang.String,java.lang.String>)
2 Answers

This is how you can achieve it.

Create the class for Tuples. Include all the field which you want to get. In your case, the first and last names are the fields. This is concept is called Returning subsets of columns.

UserNameTuple

data class UserNameTuple(
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?
)

Design the query like this:

@Query("SELECT first_name, last_name FROM user WHERE id = :id")
fun getUserName(id: String): List<UserNameTuple>

You will get the data that satisfied the query condition with the tuple data.

This is how you can achieve it in your application.

You can also use secondary constructor in you User Class like below:

constructor(first_name: String, last_name: String) : this("", first_name, last_name)

Or since you have more field then you can use default value to avoid secondary constructor like below [I put "", you can change it according your requirements]:

data class User(
   var id: String = "",
   var first_name: String = "",
   var last_name: String = ""
   // some other fields
)

And modify getUserName like this

@Query("SELECT first_name, last_name FROM user WHERE id = :id")
fun getUserName(id: String): User
Related