Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala have syntax for 0- and 1-tuples?

Tags:

scala> val two = (1,2) two: (Int, Int) = (1,2)  scala> val one = (1,) <console>:1: error: illegal start of simple expression        val one = (1,)                     ^  scala> val zero = () zero: Unit = () 

Is this:

val one = Tuple1(5) 

really the most concise way to write a singleton tuple literal in Scala? And does Unit work like an empty tuple?

Does this inconsistency bother anyone else?

like image 272
Jay Hacker Avatar asked Aug 26 '11 16:08

Jay Hacker


People also ask

Does Scala have tuples?

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.

Can a tuple be 1 element?

To generate a tuple with one element, a comma , is required at the end. For example, when connecting multiple tuples with the + operator, note that an error is raised if you try to add one element and forget a comma , .

Can we have variables of different types inside of a tuple in Scala?

Thankfully, Scala already has a built-in tuple type, which is an immutable data structure that we can use for holding up to 22 elements with different types.

Are tuples mutable Scala?

A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. Type of tuple is defined by, the number of the element it contains and datatype of those elements.


1 Answers

really the most concise way to write a singleton tuple literal in Scala?

Yes.

And does Unit work like an empty tuple?

No, since it does not implement Product.

Does this inconsistency bother anyone else?

Not me.

like image 107
Kim Stebel Avatar answered Sep 21 '22 02:09

Kim Stebel