https://kotlinlang.org logo
Title
i

iex

02/19/2020, 6:38 AM
Can anyone please shed light into this? Seems Java interop issues
class Foo<T> {
    fun <T> foo(a: T, b: T) = a == b // compiles
}

class MyCallback<T> : DiffUtil.ItemCallback<T>() {
    override fun areItemsTheSame(oldItem: T, newItem: T): Boolean =
        throw Error("TODO")

    override fun areContentsTheSame(oldItem: T, newItem: T): Boolean =
        oldItem == newItem // Doesn't compile - "equals in not implemented on T"
}
k

Kune Keiseiie

02/19/2020, 7:19 AM
What about
MyCallback<T : Any>
?
m

molikuner

02/19/2020, 8:09 AM
So I don’t know why it doesn’t compile for you, as it does for me 🤷‍♂️🏻 . But there is definitely a difference between those two functions:
println(MyCallback<String>().areContentsTheSame("a", "b"))
println(Foo<Int>().foo<String>("a", "b"))
As you can see the
T
of
Foo.foo()
is a different than the
T
of
Foo
. Thats not possible in the
MyCallback
implementation.
i

iex

02/19/2020, 11:29 AM
@Kune Keiseiie I remember trying with
Any
and it didn't change anything, weirdly
😱 1
@molikuner ah my bad, The
T
in
foo
is scoped to the function of course. But this doesn't explain the problem, does it? 🤔
it should have been
class Foo<T> {
    fun foo(a: T, b: T) = a == b // compiles
}
but it still works... 😄
m

molikuner

02/19/2020, 11:36 AM
No, and unfortunately I can’t reproduce your error: https://pl.kotl.in/pKgRjxlHh
i

iex

02/19/2020, 11:47 AM
may it be because the callback I'm extending was declared in Java? This is why I attributed it to java interop...
it's the
DiffUtil
used in
RecyclerView
a

Andrew

02/19/2020, 5:20 PM
It looks like this issue is specific to DiffUtil and is really just a lint warning not a "real" compiler error. The reason is the default equality operator checks if the object references are the same and the whole purpose of DiffUtil is to check that they represent the same data because the list changed and all the objects are technically different even if nothing changed. If T is limited to a class that overrides equals() this error goes away. https://issuetracker.google.com/issues/116789824
By lint warning I mean lint rule that is set to error, it can be changed in settings but I would recommend leaving as is since the code can be changed to work + get the type safety you want