我有一个可以接收 List[tuple3(foo, bar, fooby)] 的函数,并且我意识到我想在使用 List[tuple4(foo, bar, fooby, foobar)] 时使用相同的函数。我想我可以对此使用模式匹配,但这会导致代码重复。我该怎么办?
val tuple3List : List[(Foo, Bar, Fooby)] = List()
val tuple4List : List[(Foo, Bar, Fooby, Foobar)] = List()
myFunc(tuple3List)
myFunc(tuple4List)
def myFunc(tupleList : List[Foo, Bar, Fooby]) = {
}
最佳答案
Tuple3
是 Product3
的子类型,Tuple4
是 Product4
的子类型...
Product3
、Product4
...是Product
的子类型。
所以你可以尝试
val tuple3List : List[(Foo, Bar, Fooby)] = List()
val tuple4List : List[(Foo, Bar, Fooby, Foobar)] = List()
myFunc(tuple3List)
myFunc(tuple4List)
def myFunc(tupleList : List[Product]) = {
// Do stuff
}
“参数数量不足的元组”的另一个替代可能是 shapeless.HList .
关于scala - 函数可以接收参数数量不确定的元组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55742545/