Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data class empty constructor for Firebase

data class MainPosts(val context: Context, val posts: Posts, val livePost: LivePosts?)
{
    constructor() : this(null!!, null!!, null!!) 
}

Hey, I've been trying to figure out how to create an empty constructor on data class for Firebase.

I tried that code which is above but it didn't work properly.

like image 779
Burak Taban Avatar asked Feb 02 '26 15:02

Burak Taban


2 Answers

To get a default constructor, you should initialize the values:

data class MainPosts(
    val context: Context = someDefaultValue1, 
    val posts: Posts = someDefaultValue2, 
    val livePost: LivePosts? = null) 

If they are all nullable as it seems from your constructor code:

data class MainPosts(
    val context: Context? = null, 
    val posts: Posts? = null, 
    val livePost: LivePosts? = null) 

This give you a default constructor.

like image 83
Jan Vladimir Mostert Avatar answered Feb 05 '26 04:02

Jan Vladimir Mostert


Nice answers already suggested. However, another way to go is to use the no-args compiler plugin which generates a synthetic no argument constructor. It's specifically designed for such situations where providing default parameters might not be desirable.

Checkout No-arg compiler plugin

like image 38
Kingsley Adio Avatar answered Feb 05 '26 05:02

Kingsley Adio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!