首页 > 解决方案 > 执行列表中的函数

问题描述

我在 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 方法中调用列表并执行它?

标签: scala

解决方案


给定

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))

斯卡斯蒂


推荐阅读