Given that `Entry` has a `toPair()` method, why do...
# stdlib
n
Given that
Entry
has a
toPair()
method, why does
Pair
does not have a
toEntry()
method?
p
Probably because there’s no single concrete Entry class to create
d
Also, what do you need an
Entry
for?
e
there is a concrete implementation in modern Java,
AbstractMap.SimpleEntry
- but from the Kotlin's perspective, you have to choose between
Map.Entry
and
MutableMap.MutableEntry
. also in line with Dominic's point, there are Kotlin APIs that accept
Pair
, but what do you want an
Entry
for?
n
I want it because I have to work with a foreign (Java) API which requires entries as parameters. And while yes, I would have to choose, given that pairs are mutable, MutableEntry would be the natural choice.
e
kotlin.Pair
is not mutable
n
yes, sorry got that twisted. Maybe toEntry and toMutableEntry would do the trick
e
your options are to either use the Java concrete classes or write your own:
Copy code
fun <K, V> Pair<K, V>.toEntry() = object : Map.Entry<K, V> {
    override val key: K = first
    override val value: V = second
}
I don't think these would get much use in stdlib given that all other APIs (such as
Iterable<Pair<K, V>>.toMap()
) are based around
Pair
d
Surprised you didn't go for an inline class. I suppose it would get boxed almost immediately.
e
Map.Entry
is an interface so a
@JvmInline value class MyEntry<out K, out V>(pair: Pair<K, V>) : Map.Entry<K, V>
would get immediately boxed, yes. and it would have to hold on to the original
Pair
since value classes don't support multiple values yet, and it would be impossible to implement
MutableEntry
this way
n
that "own" is what I am using. Was really trying to understand the rationale for the imbalance (Entry->Pair exists, but reverse does not).
d
Entry
exposes a key and a value but Pair doesn't have such semantics so there's no "correct" way to create an
Entry
from a
Pair
. The other direction is possible as a lossy conversion though.
n
The same decision has to be made in the existing Entry->Pair method: should the key be the first of the second value in the pair? So there is consistent way (which is IMHO more important than "correct" in this case).
The documentation outlines the decision I suppose.
Represents a key/value pair held by a Map.
Key first and value second.