https://kotlinlang.org logo
Title
o

oday

11/07/2019, 10:28 AM
im really unsure why this is happening
j

jwinwood

11/07/2019, 10:33 AM
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

oday

11/07/2019, 10:34 AM
ahh...yes I thought its weird why it kept prepending
Collections....
before the datatype
j

jwinwood

11/07/2019, 10:34 AM
if your function returned
Single<Map<String, List<Products>>>
then
toMap
should work?
o

oday

11/07/2019, 10:34 AM
Map doesnt have constructors
j

jwinwood

11/07/2019, 10:35 AM
you can use
mutableMapOf
o

oday

11/07/2019, 10:37 AM
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

jwinwood

11/07/2019, 10:37 AM
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

oday

11/07/2019, 10:38 AM
now its mapping the name to the rest of the parent json object, which is not Product, its ProductListing
it does suffice, yes
j

jwinwood

11/07/2019, 10:43 AM
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

oday

11/07/2019, 10:52 AM
thank you it makes total sense
j

jwinwood

11/07/2019, 10:54 AM
no problem, glad I could help
o

oday

11/07/2019, 10:57 AM
and it resolved all of my issues, went back to what i originally wanted, a String/List<Product> map
thanks again
w

wbertan

11/07/2019, 11:02 AM
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)