我需要一个方法来接收未知长度的元组(Tuple2、Tuple3 或 TupleX)并返回元组元素列表。我写了下面的方法,但我得到一个错误,它不能转换类型 Any
至 String
在列表中:
def toList(tuple: Product): List[String] = tuple match {
case (s1, s2) => List(s1, s2)
case (s1, s2, s3) => List(s1, s2, s3)
}
您能否帮助修复上述示例或提出其他解决方案?
最佳答案
全部 TupleN
类型继承自 Product
, 和 Product
有方法productIterator
( documentation link ),所以你可以写:
def toList(tuple: Product): List[String] =
tuple.productIterator.map(_.asInstanceOf[String]).toList
请注意,这不是类型安全的。每当您传递不是
String
元组的任何内容时,它都会抛出错误。对它。您可能想调用 _.toString
反而。
关于scala - 将未知长度的元组转换为 Scala 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49149070/