【问题标题】:convert a method call with parameters to a Function that takes no parameters将带参数的方法调用转换为不带参数的函数
【发布时间】:2018-02-05 02:13:39
【问题描述】:

从不带参数的方法调用创建函数需要以下语法:-

val d = 显示 _

如何对带参数的方法调用做同样的事情。 请在下面找到示例代码。

package paf

/**
  * Created by mogli on 8/27/17.
  */
object PafSample {

  def display(): Unit ={
    println("display is a no argument method")
  }

  def evenOdd(input : Int) : Unit = if(input % 2 == 0) println(s"$input is even")  else println(s"$input is odd")

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

    //This is working
    val d = display _
    executeFunction(d)

    //TODO : convert to a function call that takes no arguments,
    //       so that, it can be passed to executeFunction as parameter

    //val e = evenOdd(3) _
    //executeFunction(e)
  }

  def executeFunction[B](f : () => B) : B = {
    println("executing function")
    f()
  }
}

【问题讨论】:

    标签: scala function methods


    【解决方案1】:

    那是行不通的。 executeFunction 是一种采用函数的方法,该函数接受参数并返回 BevenOdd 接受Int 类型的单个参数并产生Unit,即Int => Unit

    您需要接受一个参数:

    def executeSingleArgFunction[A, B](a: A)(f: A => B): B = {
        f(a)
    }
    

    然后:

    executeSingleArgFunction(3)(evenOdd)
    

    【讨论】:

    • val d=显示_; executeSingleArgFunction(())(d) 给出 CTE。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2022-06-23
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多