给出一个Tuple3,例如("one", "two", "three")
我想获取tuple2,它只包含前两个元素("one", "two")
。
这样做的一种方法是:
val (one, two, _) = ("one", "two", "three")
val result = (one, two)
但是如果我想从tuple16获取类似的东西怎么办呢?样板。
更新
更具体的用例(func2和func3无法更改)。
def func3(one: String, two: String, three: String) = println("Do something")
def func2(one: String, two: String) = println("Do something 2")
val originalTuple = ("one", "two", "three")
val newTuple = ???
(func3 _).tupled(originalTuple)
(func2 _).tupled(newTuple)
答案 0 :(得分:7)
您可以尝试使用Shapeless 2.0中的take
/drop
:
import syntax.std.tuple._
scala> (23, "foo", true).take(2)
res3: (Int, String) = (23,foo)
标准库中没有这样的解决方案,因为通常你不需要它。具有16种不同类型/元素的元组没有任何意义,并且是不良风格的明显标志。通常这样的元组可以表示为嵌套的案例类,但有时(非常非常罕见)您可能需要这样的东西来提高类型安全性。这就是为什么Shapeless存在的原因。
答案 1 :(得分:3)
这对前两个元素都可以。
scala> val tuple3 = ("one","two","three")
tuple3: (String, String, String) = (one,two,three)
scala> (tuple3._1, tuple3._2)
res8: (String, String) = (one,two)