https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

diego.brum

03/24/2021, 3:30 PM
Hello all, in C# we have Tuple class (a helper class) to make easy use destructor, for instance
Copy code
var (x, y) = Tuple.Create("hello", "world");
// or
var (x, y) = ("hello", "again");
// or also
var x = ("hello", "again");
x.Item1 // hello
x.Item2 // again
// or also also
var x = (Xpto: "Hello", Yup: "Again")
x.Xpto 
x.Yup
in Kotlin I had read about destructors and find the Pair class Is it the equivalent? And is it possible initialise "Pair" on the fly like C#?
r

Ruckus

03/24/2021, 3:37 PM
You can use
to
to make a `Pair`:
val (x, y) = "hello" to "again"
Copy code
val x = "hello" to "again"
x.first
x.second
There's also a
Triple
class, but Kotlin does not have tuples, so you cannot create arbitrary sizes or use custom keys.
d

diego.brum

03/24/2021, 3:39 PM
Nice, tks 🙂
c

Casey Brooks

03/24/2021, 3:43 PM
ad-hoc objects can be helpful intermediate types for data processing, where you may have been using tuples before https://kotlinlang.org/docs/object-declarations.html#object-expressions
d

diego.brum

03/24/2021, 3:47 PM
NIce one! Tks 🙂
r

Ruckus

03/24/2021, 4:16 PM
Wow, I've been using Kotlin for years and wasn't aware of that (the object expression without super types working privately). Thanks for the pointer.
j

Jordan Foo

03/24/2021, 4:40 PM
Also @diego.brum, typeAliases can make it cleaner to read and use
Copy code
typealias MyPair = Pair<String, Int>
and
Copy code
val myPair: MyPair = "myString" to 1
val (myString, myInt) = myPair
❤️ 2
Helps for when you're using a pair as a composite key for maps, for example (which is valid because the pair implementation is a data class, which overwrites equals and hashcode)
6 Views