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

标签 scala

我有一个可以接收 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/

相关文章:

scala - com.eed3si9n#sbt-assembly的libraryDependencies; 0.13.0 : not found

scala - 用 HashMap[Int, Vector[Int]] (Scala) 表示图(邻接表)?

Scala 映射和对操作

scala - Scala 是否有相当于 ML 的 "as"构造的语句?

scala - Intellij Idea - Scala 使用什么配置

scala - 如何在 Scala 中重构嵌套的 Option.folds?

Scala 的元组展开细微差别

scala - Scala 中高级类型的类型类实例中的两个参数函数,如何将这个简单的 Haskell 代码转换为 Scala?

java - 如何在scala中生成protobuf?

scala - Currying 与 Currying 的有用性(在实际应用中) Scala 中的部分应用