https://kotlinlang.org logo
#stdlib
Title
# stdlib
n

nkiesel

06/17/2022, 7:33 PM
Given that
Entry
has a
toPair()
method, why does
Pair
does not have a
toEntry()
method?
p

Paul Griffith

06/17/2022, 7:40 PM
Probably because there’s no single concrete Entry class to create
d

Dominaezzz

06/17/2022, 7:46 PM
Also, what do you need an
Entry
for?
e

ephemient

06/17/2022, 7:54 PM
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

nkiesel

06/17/2022, 7:58 PM
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

ephemient

06/17/2022, 7:59 PM
kotlin.Pair
is not mutable
n

nkiesel

06/17/2022, 8:00 PM
yes, sorry got that twisted. Maybe toEntry and toMutableEntry would do the trick
e

ephemient

06/17/2022, 8:09 PM
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

Dominaezzz

06/17/2022, 8:10 PM
Surprised you didn't go for an inline class. I suppose it would get boxed almost immediately.
e

ephemient

06/17/2022, 8:13 PM
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

nkiesel

06/17/2022, 8:13 PM
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

Dominaezzz

06/17/2022, 8:17 PM
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

nkiesel

06/17/2022, 8:20 PM
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.
3 Views