Scala方法形参中传入函数作为参数

在Scala中可以将函数作为参数传递到另一个方法中,代码如下:

object FunctionTest {

  def main(args: Array[String]): Unit = {
    test(plus)
  }

  def test(fun: => Unit): Unit = {
    println("this is test run")
    fun
  }

  def plus() = {
    println("this is plus run")
  }

}

运行结果:

this is test run
this is plus run

 

那么 万一这个传入的函数自己本身也有形参怎么办呢?

object FunctionTest {

  def main(args: Array[String]): Unit = {
    test(plus, 23)
  }

  def test(fun: Int => Unit, num: Int): Unit = {
    println("this is test run")
    fun(num)
  }

  def plus(num: Int) = {
    println("this is plus run" + num)
  }

}

运行结果:

this is test run
this is plus run23

 还可以写的更简洁,类似java的匿名内部类,我愿称之为匿名函数:


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值