当前位置:网站首页>Scala language learning-04-function passed in as parameter function as return value

Scala language learning-04-function passed in as parameter function as return value

2022-06-22 15:45:00 Sunshine clover lxgzxj

One 、 Exercise questions

    // practice 1: Function is passed in as a parameter 
    //func Implement incoming Int Return function f1
    
    //f1 The implementation passes in a string return function f2
    
    //f2 The implementation passes in a character and returns bool type 
    
    // Ask to execute func(0)("")('0') return false, Other situations return to true
    // practice 2: Function as return value 
    //ArrayElementOp Realization :
    // The first parameter is passed in Int Type array 
    // The second parameter is passed into the function ElementAddVal
    // Return to one Int Type array 
    
    //ElementAddVal Realization :
    // Pass in two int Type parameter 
    // Returns the addition of two numbers , The type is int

    // Test array :(1, 2, 3, 4, 5, 6)
    // Return results :(2, 4, 6, 8, 10, 12)

Two 、 Test code

object TestFuncParam {
    
    def main(args: Array[String]): Unit = {
    
        val TempArray: Array[Int] = Array(1, 2, 3, 4, 5, 6)
    
        val NewArray: Array[Int] = ArrayElementOp(TempArray, ElementAddVal)
        println(NewArray.mkString(" | "))
    
        println(func(0)("")('0'))
        println(func(1)("")('0'))
    }
    
    // practice : Function as parameter 
    def ArrayElementOp(ParamArray: Array[Int], Func: (Int,Int) => Int): Array[Int] = {
    
        for(i <- ParamArray) yield Func(i,i)
    }
    
    def ElementAddVal(Param1: Int, Param2: Int): Int = {
    
        Param1 + Param2
    }
    
    // practice : Function as return value 
    def func(Param1: Int): String => (Char => Boolean) = {
    
        def f1(Param2: String): Char => Boolean = {
    
            def f2(Param3: Char): Boolean = {
    
                if(Param1 == 0 && Param2 == "" && Param3 == '0'){
    
                    false
                }
                else {
    
                    true
                }
            }
            f2
        }
        f1
    }
    
}

3、 ... and 、 test result

[[email protected] test]# scala TestFuncParam
2 | 4 | 6 | 8 | 10 | 12
false
true
原网站

版权声明
本文为[Sunshine clover lxgzxj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221428297755.html