Hey guys, I have run into a weird situation here a...
# announcements
s
Hey guys, I have run into a weird situation here and I do not know whether this is some kind of bug or I am just dumb. (which happens from time to time ^^) This function is a minimized example of what I encountered:
Copy code
// kotlin 1.3.72
fun foo(one: Int, two: String) {
    val list = listOf(one, two)
    println(list)
}
I selected the
listOf(one, two)
part and tried to perform the "extract function" action on it, assuming that this would result in a function like
fun xxx(one: Int, two: String): List<Any> = ...
But what I actually got was an error popup saying:
Cannot extract method since following types are not denotable in the target scope:
{Comparable<{Int & String}> & java.io.Serializable}
This type is kind of understandable: Int and String are both comparable to themselves and are also serializable. But I did not understand, why this would stop me from extracting a function with type
List<Any>
. Then I tried the "Specify type explicitly" action and the type it suggested was not
List<Any>
, but
List<Comparable<Any>>
. With that type however, the code would not compile anymore, giving three errors:
Type mismatch. Required: Comparable<Any> Found: Int
Type mismatch. Required: List<Comparable<Any>> Found: List<{Comparable{Int & String}> & java.io.Serializable}>
Type mismatch. Required: Comparable<Any> Found: String
I am still having a hard time completely wrapping my head around variance, but I think that this is because it is
List<out T>
, but
Comparable<in T>
with Int and String both having the same type as their comparable T. Now here is my question(s): Is this expected behavior, or should the compiler (or the Kotlin plugin?) refrain from inferring a type that has this kind of contradiction? Is this even feasible to check? I mean this only occurs because Comparable is usually used with T being the own type, like
Int : Comparable<Int>
... Edit: As a little bonus, I just saw a thing which probably really is a bug: There are 3 quickfixes for the threefold error above: • Change type of 'list' to 'Int' • Change type of 'list' to 'List<Any>' • Change type of 'list' to 'String' Yes, the second one is what is needed here, but the other ones do not make sense... Why does it suggest to make it
val list: Int = listOf(one, two)
? 😅