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

﹥>﹥吖頭↗ 提交于 2020-12-04 14:43:31

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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
}


来源:https://stackoverflow.com/questions/7207527/does-scala-have-syntax-for-0-and-1-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!