2017-08-27 85 views
0

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

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

回答

0

这不起作用。 executeFunction是一种采用参数并返回B的函数的方法。 evenOdd采用类型为Int的单个参数并且产生Unit,意思是Int => Unit

你需要接受一个参数:

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

然后:

executeSingleArgFunction(3)(evenOdd) 
+0

VAL d =显示_; executeSingleArgFunction(())(d)给CTE。 – mogli

+0

什么是CTE?... – pedrofurla