我有一个存储匿名函数的元组,我想遍历它们并执行它们。
val functions = ((x:Int, y:Int) => x + y, (x:Int, y: Int) => x - y)
// I want to execute the anonymous functions in the Tuple
functions.productIterator.foreach(function => function)
不幸的是我做不到
functions.productIterator.foreach(function => function(1, 2))
或
functions.productIterator.foreach(_(1, 2))
什么是出路。
最佳答案
元组并不意味着被迭代。类型会丢失,因为元组中的每个条目都可以是不同的类型,因此类型系统只是假定 Any
(因此是 Iterator[Any]
)。所以真正的建议是,如果你想迭代,使用像 Seq
或 Set
这样的集合。
另一方面,如果您知道元组包含特定类型的函数,那么您可以通过使用 asInstanceOf
强制转换来绕过类型检查,但这是不推荐,因为类型检查是你的 friend 。
functions.productIterator.map(_.asInstanceOf[(Int,Int)=>Int](1, 2))
// produces `Iterator(3, -1)`
或者,查看 Shapeless 中的 HLists , 具有元组和集合的属性。
关于scala - 在 Scala 中执行元组之外的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36784566/