为什么在Scala中没有针对单元素元组的Tuple1文字?

| Python的单个元素元组具有
(1,)
。在Scala中,
(1,2)
适用于
Tuple2(1,2)
,但是我们必须使用
Tuple1(1)
来获得单个元素元组。这似乎是一个小问题,但是设计期望产品的API对于传递单个元素的用户来说是一件痛苦的事情,因为他们必须编写Tuple1(1)。 也许这是一个小问题,但是Scala的主要卖点是打字更多而打字更少。但是在这种情况下,似乎打字更多,打字更多。 请告诉我: 1)我已经错过了它,它以另一种形式存在,或者 2)它将被添加到该语言的将来版本中(他们将接受补丁程序)。     
已邀请:
        您可以定义一个隐式转换:
implicit def value2tuple[T](x: T): Tuple1[T] = Tuple1(x)
仅当参数的静态类型尚未符合方法参数的类型时,隐式转换才适用。假设您的方法接受一个
Product
参数
def m(v: Product) = // ...
例如,转换将适用于非产品值,但不适用于ѭ7。警告:所有案例类别都扩展了“ 5”特征,因此转换也将不适用于它们。相反,乘积元素将成为case类的构造函数参数。
Product
TupleX
类的最小上限,但是如果要将隐式Tuple1转换应用于所有非元组,则可以使用类型类:
// given a Tupleable[T], you can call apply to convert T to a Product
sealed abstract class Tupleable[T] extends (T => Product)
sealed class ValueTupler[T] extends Tupleable[T] { 
   def apply(x: T) = Tuple1(x) 
}
sealed class TupleTupler[T <: Product] extends Tupleable[T] { 
   def apply(x: T) = x 
}

// implicit conversions
trait LowPriorityTuple {
   // this provides a Tupleable[T] for any type T, but is the 
   // lowest priority conversion
   implicit def anyIsTupleable[T]: Tupleable[T] = new ValueTupler
}
object Tupleable extends LowPriorityTuple {
   implicit def tuple2isTuple[T1, T2]: Tupleable[Tuple2[T1,T2]] = new TupleTupler
   implicit def tuple3isTuple[T1, T2, T3]: Tupleable[Tuple3[T1,T2,T3]] = new TupleTupler
   // ... etc ...
}
您可以在API中使用此类型类,如下所示:
def m[T: Tupleable](v: T) = { 
   val p = implicitly[Tupleable[T]](v) 
   // ... do something with p
}
如果您有返回产品的方法,则可以查看如何应用转换:
scala> def m[T: Tupleable](v: T) = implicitly[Tupleable[T]](v)
m: [T](v: T)(implicit evidence$1: Tupleable[T])Product

scala> m(\"asdf\") // as Tuple1
res12: Product = (asdf,)

scala> m(Person(\"a\", \"n\")) // also as Tuple1, *not* as (String, String)
res13: Product = (Person(a,n),)

scala> m((1,2)) // as Tuple2
res14: Product = (1,2)
    
        当然,您可以向API添加隐式转换:
implicit def value2tuple[A](x: A) = Tuple1(x)
我发现ѭ15包含结尾逗号很奇怪:
scala> Tuple1(1)
res0: (Int,) = (1,)
    
        Python不是静态类型的,因此那里的元组的行为更像是固定大小的集合。 Scala并非如此,其中元组的每个元素都有不同的类型。 Scala中的元组的用法与Python中的不同。     

要回复问题请先登录注册