在Scala 2中,我有一个元组,如下所示:
val direction = (2,3)
这个值direction
我想与Int
因子f
相乘,以获得新的元组
(2 * f, 3 * f)
因此,如果f=4
,我将查找结果(8,12)
。
我尝试了明显的候选*
:
(2,3) * f
但CCD_ 7似乎并不是为这些类型而设计的。
TupleN
也有productIterator
:
(1,2,3,4,5)
.productIterator
.map { case n: Int => n * 2 }
.toList
这不会返回另一个元组,但可以在不添加任何新库的情况下轻松迭代所有元素。
productIterator
返回Iterator[Any]
,所以必须使用模式匹配。
这个怎么样?
// FUNCTION
object TupleProduct extends App {
implicit class TupleProduct(tuple2: (Int, Int)) {
def * : Int => (Int, Int) = (f: Int) => {
(tuple2._1 * f, tuple2._2 * f)
}
}
val direction = (2, 3)
print(direction * 4)
}
// METHOD
object TupleProduct extends App {
implicit class TupleProduct(tuple2: (Int, Int)) {
def *(f: Int):(Int, Int) = {
(tuple2._1 * f, tuple2._2 * f)
}
}
val direction = (2, 3)
print(direction * 4)
}