What's the correct way of accessing Scala tuple elements in Java?

moe :

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 …)?

sachav :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143514&siteId=1