https://kotlinlang.org logo
Title
s

Slawomir Ziolkowski

04/18/2020, 11:18 AM
Hi, I'm new to Kotlin. Amazing language but sometimes it confuses me a lot 🙂 Maybe someone could help me there:
fun main(args: Array<String>) {
    val firstList = listOf<User>(
            User(name="P-0"), User(name="P-0"), User(name="P-0"),
            User(name="P-2"), User(name="P-2"), User(name="P-2"), User(name="P-2")
    )
    val secondList = listOf<User>(User(name="P-2"))
    print(firstList.minus(secondList))
}

data class User(val name: String)
I expect that only one P-2 element will be not in the result, but the result looks like this: [User(name=P-0), User(name=P-0), User(name=P-0)]
d

Dan Newton

04/18/2020, 11:34 AM
it removes elements with the same hashcode afaik
if you used a
class
instead of a
data class
it should do what you want
only because a
data class
overrides the
hashCode
depending on the class’s properties
m

Mike

04/18/2020, 11:52 AM
Take a look at the
minus
or
-
function implementation in the stdlib, and you'll see it's effectively a
filter
. So basically, filter all elements from the first list that are in the second.
k

Kroppeb

04/18/2020, 11:57 AM
if you used a class instead of a data class it should do what you want
No, not using a
data class
would remove no items
s

Slawomir Ziolkowski

04/18/2020, 2:21 PM
thanks for fast responses! Is there any alternative to the minus function? I just need a list without one element from the second list.
m

molikuner

04/18/2020, 10:21 PM
s

Slawomir Ziolkowski

04/20/2020, 12:11 PM
Thanks!