Better way to get value from a data snapshot?

2020-03-26 android kotlin firebase-realtime-database operator-overloading inline

In Android Studio, using Firebase Realtime Database and Kotlin, to retrieve the value of a node, you would have the following code:

val parentNodePath: String = "nodeParentPath"
val nodePath: String = "nodePath"

val nodeRef = FirebaseDatabase.getInstance().reference.child(parentNodePath)

var value: Int

nodeRef.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(dS: DataSnapshot) {
    value = dS.child(nodePath).getValue(Int::Class.java)!!
    //or also 
    //value = dS.child(nodePath).value as Int
}

override fun onCancelled(dE: DatabaseError) {}
})

Would it be ok to define an extension function which implements the get operator overload to retrieve the value in a path, and would it be better to use inline keyword too, so when it runs, it doesn't have to call the function and instead it gets inlined inside the code?

/*inline*/ operator fun DataSnapshot.get(path: String): Any? =
    this.child(path).value

It would be used as value = dS[nodePath] as Int

Answers

Related