5

i've converted a java file to kotlin file in a recent project, the problem is that i'm facing an error with this code:

 val map = dataSnapshot.getValue<Map<*, *>>(Map<*, *>::class.java)

I'm having a red line under "Map<*, *>::class", and android studio says:

Only classes are allowed on the left hand side of a class literal

What should i do with this code? is there is any other way to write it?

Here is a relative kotlin code snippet:

val messageText = messageArea!!.text.toString()
        if (messageText != "") {
            val map = HashMap<String, String>()
            map.put("message", messageText)
            map.put("user", UserDetails.username)
            reference1!!.push().setValue(map)
            reference2!!.push().setValue(map)
            messageArea!!.setText("")
        }
    }
    reference1!!.addChildEventListener(object : ChildEventListener {
        override fun onChildAdded(dataSnapshot: DataSnapshot, s: String) {
            val map = dataSnapshot.getValue<Map<*, *>>(Map<*, *>::class.java)
            val message = map.get("message").toString()
            val userName = map.get("user").toString()

Original java code snippet:

String messageText = messageArea.getText().toString();

            if(!messageText.equals("")){
                Map<String, String> map = new HashMap<String, String>();
                map.put("message", messageText);
                map.put("user", UserDetails.username);
                reference1.push().setValue(map);
                reference2.push().setValue(map);
                messageArea.setText("");
            }
        }
    });

    reference1.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Map map = dataSnapshot.getValue(Map.class);
            String message = map.get("message").toString();
            String userName = map.get("user").toString();
Chad Bingham
  • 32,650
  • 19
  • 86
  • 115
AlHasan Ali
  • 53
  • 1
  • 5

2 Answers2

5

Try casting it.

val map = dataSnapshot.getValue(Map::class.java) as Map<String, String>

You may want to suppress warnings for "Unchecked Cast", but that is ok.

Chad Bingham
  • 32,650
  • 19
  • 86
  • 115
2

Based on the answer to this question you have the option to use Kotlin's reified feature and implement something like this to extend DataSnapshot.

inline fun <reified T> DataSnapshot.getValue(): T? {
    return getValue(T::java.class)
}

Or based on Firebase's documentation of DataSnapshot you can get the map value like this.

val map = dataSnapshot.getValue()
if (map is Map<*, *>) {
    val message = map["message"].toString()
    val userName = map["user"].toString()
}
jasperagrante
  • 354
  • 4
  • 17