Is tuple syntax of `(a, b)` coming to Kotlin, same...
# getting-started
u
Is tuple syntax of
(a, b)
coming to Kotlin, same like Swift has?
e
Kotlin doesn't have generic tuples beyond
Pair
and
Triple
and prevailing style is to create your own named
data class
for each need
plus1 2
there's been some discussion about tuples in https://youtrack.jetbrains.com/issue/KT-45587 - more about whether they belong in the language than the syntax for creating instances
u
for public api yes, but for internals tuples are very convenient
e
as far as syntax goes, I imagine there will be no decision until https://youtrack.jetbrains.com/issue/KT-43871
u
yes that was my followup, that
listOf(..)
to
[..]
smells lot like
Pair(…)
to
(…)
c
I don't think
(…)
will ever be added, it looks too much like existing syntax. However, I wouldn't be surprised that pairs benefit from the collection literals syntax:
Copy code
val a: Pair<Int, String> = [5, "foo"]
s
just for completeness, the idiomatic way to instanciate a Pair is via the infix function
to
, so it's:
a to b
example
2
u
a to b to c to d
is just letter soup 😕
e
well you wouldn't ever chain them like that, infix associativity doesn't make sense
u
so triple needs to be
Triple(a,b,c)
? I guess the normal
(..)
syntax is even more necessary...
s
@CLOVIS I don't see how the syntax
(...)
conflicts with existing syntax. Assuming you're talking about destructuring syntax, destructuring itself is kinda like a stripped down and limited version of extracting a tuple's fields. The Kotlin team has made it clear that if they implement this, it will be named tuples, and they're basically just objects without a name, which can be very useful for many use-cases. Rust has un-named tuples, and while they're not used a lot as return types, they make some APIs very clean (e.g.
partition
splits a list in two parts, so it returns a
(Vec<T>, Vec<T>)
tuple, instead of a list of lists). Having named tuples in Kotlin is gonna bring the same benefits, but with much better ergonomics and syntax. E.g. in Rust, while it's more common to destructure tuples, to access an element you have to do
my_tuple.0
or
.1
or whatever is the order, and even IDE actions can't suggest proper names in destructuring. Named tuples don't suffer from this issue, but also without requiring you to make an entire class for a single use.