Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Nested Object Classes

Ok so i'v been starting to learn kotlin for a week now, and i love the language:p Besides the great utility of extension function, i feel like they lack a proper way of creating namespaces like java utility classes (xxxUtil).

I have recently starting to use this aproach, which im not sure is the right one, and i would like some feedback from Kotlin experienced users.

Is this a valid and proper thing todo:

object RealmDb {

   private val realmInstance by lazy{ Realm.getInstance(MainApplication.instance) }

   private fun wrapInTransaction(code:() -> Unit){
       realmInstance.beginTransaction();
       code.invoke()
       realmInstance.commitTransaction();
}
   object NormaNote{
      fun create(...) {...}
      fun update(...) {...}
   }
}

So, whenever i want to update some NormalNote value to a Realm Database, i do the following:

RealmDb.NormaNote.create(title.text.toString(), note.text.toString())

Is this a common thing to do? Are there better approaches? As i understood, this is singleton nesting, i don't think there's any problem with this, i just don't like to put this common things like DB operations inside classes that need to be instantiated. In old java i opted to static classes

like image 548
johnny_crq Avatar asked Feb 21 '26 14:02

johnny_crq


1 Answers

The officially recommended way to create namespaces in Kotlin is to put properties and functions that don't need to be inside classes at the top level of the file, and to use the package statements to create a namespace hierarchy. We see the practice of creating utility classes in Java as a workaround for a deficiency in the language, and not as a good practice to be followed in other languages.

In your example, I would put all of the code in top-level functions and properties.

like image 161
yole Avatar answered Feb 23 '26 21:02

yole