im really unsure why this is happening
# getting-started
o
im really unsure why this is happening
j
Your function returns type
Single<HashMap<String, List<Product>>>
,
toMap
will return the Kotlin stdlib Map interface. HashMap is based on Java collection, and the Kotlin compiler won't know how to cast a Kotlin Map to a HashMap
o
ahh...yes I thought its weird why it kept prepending
Collections....
before the datatype
j
if your function returned
Single<Map<String, List<Products>>>
then
toMap
should work?
o
Map doesnt have constructors
j
you can use
mutableMapOf
o
I think the main issue here is that the datatype returned also doesnt match the right hand side of whats being assigned in that mapping function
i want to map the name from the json response, to a list of objects under a different field in the same json response
j
Copy code
class Repository(
    private val apiService: ApiService
) : IRepository {
    
    override fun getProducts(): Single<Map<String, List<Product>>> =
        apiService.getProducts().map { productListings ->
            productListings.groupBy {it.name}.toMap()
        }
}
Should that not suffice?
o
FDF44501-FB48-4861-B85C-6DA444D3B28F.jpg
now its mapping the name to the rest of the parent json object, which is not Product, its ProductListing
it does suffice, yes
j
Copy code
class Repository(
    private val apiService: ApiService
) : IRepository {

    override fun getProducts(): Single<Map<String, List<Product>>> =
        apiService.getProducts().map { productListings ->
            val productsMap = mutableMapOf<String, List<Product>>()
            productListings.groupBy {it.name}
            productListings.foreach { listing ->
                productsMap.put(listing.name, listing.product)
            }
            productsMap
        }
}
I'm sure there is a more functional way of doing it but I think this should work
o
thank you it makes total sense
j
no problem, glad I could help
o
and it resolved all of my issues, went back to what i originally wanted, a String/List<Product> map
thanks again
w
Copy code
data class Asas(val id: Int, val name: String)
            val list = listOf<Asas>()
            val asas: HashMap<String, List<Asas>> = HashMap(list.groupBy { it.name })
Can create a
HashMap
from the
groupBy
?! (Not tested the code above)