如何在 Scala 中将元素附加或前置到元组 [英] How to append or prepend an element to a tuple in Scala
本文介绍了如何在 Scala 中将元素附加或前置到元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个元组,想在不失去类型安全性的情况下添加一个元素.这就是我想要实现的目标:
I have a tuple and want to add an element without loosing type safety. This is what I want to achieve:
val tuple = ("", 1, 1f) // (String, Int, Float)
val newTuple:(String, Int, Float, Double) = tuple :+ 1d
推荐答案
值得注意的是,您还可以为此编写一个代码生成器,只需几行:
It's worth noting that you can also write a code generator for this in a few lines:
val tupadd = for (n <- 2 to 20) yield {
val t = (0 until n).map(i => ('A'+i).toChar).mkString(", ")
val u = ('A'+n).toChar
val i = (0 until n).map(i => "x._"+(i+1)).mkString(", ")
List(
s"implicit class TupOps$n[$t](val x: ($t)) extends AnyVal {",
s" def :+[$u](y: $u) = ($i, y)",
s" def +:[$u](y: $u) = (y, $i)",
"}"
).mkString("\n")
}
打印出来,将它们保存在一个文件中,你就可以开始了:
Print these out, stick 'em in a file, and you're good to go:
scala> implicit class TupOps2[A, B](val x: (A, B)) extends AnyVal {
| def :+[C](y: C) = (x._1, x._2, y)
| def +:[C](y: C) = (y, x._1, x._2)
| }
defined class TupOps2
scala> (1,"salmon") :+ true
res15: (Int, String, Boolean) = (1,salmon,true)
这篇关于如何在 Scala 中将元素附加或前置到元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文