gpt4 book ai didi

scala - 函数可以接收参数数量不确定的元组吗?

转载 作者:行者123 更新时间:2023-12-02 09:07:56 25 4
gpt4 key购买 nike

我有一个可以接收 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]) = {
}

最佳答案

Tuple3Product3 的子类型,Tuple4Product4 的子类型...

Product3Product4...是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com