Home » Android » android – Empty constructor for kotlin object to use Firebase

android – Empty constructor for kotlin object to use Firebase

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m trying to save an object inside Firebase database from Kotlin,
I dont feel right providing a default empty constructor and put values as nullable, having to change all my code bc of this.

My class:

class Video(var id: String, var url: String, var owner: User) :  {
    constructor() : this("", "", User("", "", ""))
}

Firebase push:

FirebaseDatabase.getInstance().reference.child("public").push().setValue(video)

Error:

is missing a constructor with no arguments

Is there a better solution for this?

How to&Answers:

Use default arguments:

class Video(var id: String = "", var url: String = "",
    var owner: User = User("", "", ""))

(also, consider using val).

Answer:

I have not tested if it works with Firebase, but according to the kotlin documentation,

NOTE: On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.

So I suppose, by applying default values for all the constructor parameters will generate the parameterless constructor for you.

Answer:

You need to add an empty constructor to the Video class. This is required to be able to use classes with Firebase.