Scala 有 0 元组和 1 元组的语法吗?
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 = ()
这
val one = Tuple1(5)
真的是在 Scala 中编写单例元组文字的最简洁方法吗? Unit
是否像空元组一样工作?
这种不一致会打扰其他人吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。
不,因为它没有实现
Product
。不是我。
Yes.
No, since it does not implement
Product
.Not me.
这确实是编写元数为 1 的元组的最简洁的方法。
在上面的评论中,我看到许多引用“为什么 Tuple1 很有用”。
Scala 中的元组扩展了
Product
特征,它允许您迭代元组成员。可以实现一个具有
Product
类型参数的方法,在这种情况下,Tuple1
是迭代具有多种类型的固定大小集合而不丢失类型信息的唯一通用方法。使用 Tuple1 还有其他原因,但这是我最常见的用例。
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 caseTuple1
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.我从未见过使用
Tuple1
的情况。我也无法想象一个。在人们确实使用它的 Python 中,元组是固定大小的集合。 Scala 中的元组不是集合,它们是类型的笛卡尔积。因此,
Int x Int
是一个Tuple2[Int, Int]
,或简称为(Int, Int)
。当然,Int
就是Int
,没有任何类型是毫无意义的。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 aTuple2[Int, Int]
, or(Int, Int)
for short. Naturally, anInt
is anInt
, and no type is meaningless.前面的答案给出了 1 个元素的有效元组。
对于零个元素之一,此代码可以工作:
The previous answers have given a valid Tuple of 1 element.
For one of zero elements this code could work: