我需要一个接收未知长度的元组(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)
}
Run Code Online (Sandbox Code Playgroud)
您能否帮助修复上述示例或提出另一种解决方案?
所有TupleN类型都继承自Product,并且Product具有方法productIterator(文档链接),因此您可以编写:
def toList(tuple: Product): List[String] =
tuple.productIterator.map(_.asInstanceOf[String]).toList
Run Code Online (Sandbox Code Playgroud)
请注意,这不是类型安全的.每当你传递任何不是Strings 元组的东西时,它都会抛出错误.你可能想打个电话_.toString.
| 归档时间: |
|
| 查看次数: |
476 次 |
| 最近记录: |