Daniel Gomez Rico
Daniel Gomez Rico

Reputation: 15936

Empty constructor for kotlin object to use Firebase

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?

Upvotes: 8

Views: 6474

Answers (3)

shoheikawano
shoheikawano

Reputation: 1175

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.

Upvotes: 5

PaulNunezM
PaulNunezM

Reputation: 3227

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

Upvotes: 0

Cedric Beust
Cedric Beust

Reputation: 15608

Use default arguments:

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

(also, consider using val).

Upvotes: 27

Related Questions