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:
开发者_StackOverflowval 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?
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.
It really is the most concise way to write a tuple with an arity of 1.
In the comments above I see many references to "why Tuple1 is useful".
Tuples in Scala extend the Product
trait, which lets you iterate over the tuple members.
One can implement a method that has a parameter of type Product
, and in this case Tuple1
is the only generic way to iterate fixed size collections with multiple types without losing the type information.
There are other reasons for using Tuple1
, but this is the most common use-case that I had.
I have never seen a single use of Tuple1
. Nor can I imagine one.
In Python, where people do use it, tuples are fixed-size collections. Tuples in Scala are not collections, they are cartesian products of types. So, an Int x Int
is a Tuple2[Int, Int]
, or (Int, Int)
for short. Naturally, an Int
is an Int
, and no type is meaningless.
The previous answers have given a valid Tuple of 1 element. For one of zero elements this code could work:
object tuple0 extends AnyRef with Product {
def productArity = 0
def productElement(n: Int) = throw new IllegalStateException("No element")
def canEqual(that: Any) = false
}
精彩评论