how do i get rid of `unchecked casts` warning on t...
# announcements
h
how do i get rid of
unchecked casts
warning on these lines
(json["test"] as MutableMap<String, Any>)["nodes"] as java.util.ArrayList<MutableMap<String, String>>
. Example
Copy code
import com.fasterxml.jackson.databind.ObjectMapper 
private fun parseCarId(response: String): String {
    val json = ObjectMapper().readValue(response, Map::class.java) as MutableMap<String, Any>
    val cars = (json["test"] as MutableMap<String, Any>)["nodes"] as java.util.ArrayList<MutableMap<String, String>>
    val first: MutableMap<String, String> = cars.first { it["carType"] == "tesla" }
    return first["id"].orEmpty()
}
. I tried something like this so far but now Im getting a compile time error
Copy code
private fun parseCarId(response: String): String {
    val json = ObjectMapper().readValue(response, Map::class.java) as MutableMap<String, Any>
    val cars = (json["test"] as MutableMap<*, *>)["nodes"] as java.util.ArrayList<*>
    val first: MutableMap<String, String> = cars.first { it["carType"] == "tesla" }
    return first["id"].orEmpty()
}
m
Well if you want to have it really safe 😄
Copy code
private fun parseCarId(response: String): String {
	val json = ObjectMapper().readValue(response, Map::class.java) ?: return ""
	val cars = (json["test"] as? Map<*, *>)?.get("nodes") as? List<*> ?: return ""
	val first = cars.filterIsInstance<Map<*,*>>().firstOrNull { it["carType"] == "tesla" } ?: return ""
	return first["id"] as? String ?: ""
}
Or more functional:
Copy code
private fun parseCarId(response: String) =
	ObjectMapper()
		.readValue(response, Map::class.java)
		?.let { it["test"] as? Map<*, *> }
		?.let { it["nodes"] as? List<*> }
		?.filterIsInstance<Map<*,*>>()
		?.firstOrNull { it["carType"] == "tesla" }
		?.let { it["id"] as? String }
		.orEmpty()
h
Thanks @Marc Knaup
I like the fp approach