scala - 执行列表中的函数
问题描述
我在 scala 中有对象,我在其中定义了一些函数。
Object Sample {
val listFunction = Seq(func1(a,b),func2(p,q))
def func1(a: Int,b : Int) : Int ={
val c = a+b
c
}
def func2(p: Int,q : Int) : Int ={
val d = p+q
}
}
def main(args: Array[String]): Unit = {
//Want to call the list and execute the functions
ListFunction
}
如何在 main 方法中调用列表并执行它?
解决方案
给定
def func1(a: Int, b: Int): Int = a + b
def func2(p: Int, q: Int): Int = p + q
考虑之间的区别
val x: Int = func1(2, 3) // applied function
val f: (Int, Int) => Int = func1 // function as value
因此,当您将函数传递给序列时,您必须像这样使用函数作为值
val listFunction: Seq[(Int, Int) => Int] = Seq(func1, func2)
然后映射列表以应用功能
listFunction.map(f => f.apply(2, 3))
listFunction.map(f => f(2, 3))
listFunction.map(_(2, 3))
推荐阅读
- ruby - 使用内存 > 'maxmemory' 时不允许调试 Redis OOM 命令
- c++ - 在C++中多线程一个while循环
- postgresql - Debezium 心跳动作未触发
- c# - JsonSerializer.DeserializeAsync
不反序列化 - php - PHP类型化属性,如何定义对象的默认值
- css - Nextjs Material UI CSS 在首次访问时未正确加载
- c# - CSV 助手在 v22 中没有更多的设置器了吗?
- powershell - 在 Powershell Get-ADUser 查询中过滤具有未知数量的前导零的扩展属性
- sql - SQL Server 结果与 Oracle 结果不匹配
- typescript - getStaticProps 返回空的 props 对象