Reputation: 1806
I noticed that I can acces the elements from a Scala Tuple
in Java by either using the field (e.g. _1
) or a method (e.g. _1()
). Is there a "better" way of doing this for any reason (technical, canon …)?
Upvotes: 3
Views: 785
Reputation: 1316
If you analyse the definition of Tuple2
in the standard library:
final case class Tuple2[@specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T1, @specialized(Int, Long, Double, Char, Boolean/*, AnyRef*/) +T2](_1: T1, _2: T2)
extends Product2[T1, T2]
If you replicate this definition into your own MyTuple2
and look at the bytecode, you will indeed notice that _1
and _2
are declared as public fields. However, if you remove the @specialized
annotation on a field, the field becomes private, like for any regular case class. I could not find any information on why this happens, but it is probably out there deep in the Scala compiler doc. The field becomes public if the annotation is there, even if it is empty and no specialized types are specified.
So I would stay, stick with the methods _1()
and _2()
to be safe.
Upvotes: 4