Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: Create tuple from java?

Tags:

java

tuples

scala

I must have missed something obvious, but how do you create a scala-tuple in Java.

I have a scala interface that is implemented in java (for now) and includes the return of a tuple, but how do I implement it?

like image 873
Bjorn J Avatar asked Nov 22 '11 21:11

Bjorn J


People also ask

What is Tuple2 in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method. A tuple with two elements can be created as follows: Scala 2 and 3.

Is there a tuple in Java?

In Java, a tuple is a generic data structure that treats each element as an object, and these objects stores in a separate byte array. In other words, we can also say that tuple is an ordered collection of objects of different types.

What is difference between list and tuple in Scala?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.


1 Answers

A tuple is only syntactic sugar for the class Tuple2:

new Tuple2<String, String>("foo", "bar");

will do the trick in Java.

scala> ("foo", "bar")
res0: (java.lang.String, java.lang.String) = (foo,bar)

scala> new Tuple2[String, String]("foo", "bar")
res1: (String, String) = (foo,bar)

scala> ("foo", "bar").getClass.getName
res3: java.lang.String = scala.Tuple2

There are similar Tuple3 ... Tuple22 classes.

like image 93
Matthew Farwell Avatar answered Sep 30 '22 18:09

Matthew Farwell