Scala方法和函数

/**

* 2.递归方法

* 递归方法要显式的声明函数的返回值类型

def fun(num:Int):Int={

    if (num==1) {

       1

     } else {

       num*fun (num-1)

     }

}

printIn(fun(num =5))

 

/**

*  3.参数有默认值的方法

def fun (a:Int=10,b:Int=20) = { 

   a+b

}

println(fun(b=200))  (b=200传参到b:lnt=20,值为210)

 

/**

* 4.可变长参数的方法

def fun ( s:String* ) :Unit = {

    s. foreach(elem => {printIn(elem)})

        for(elem<-s) {

            println(elem)

       }

}

fun ("hello", "a", "b","c)

 

//* def fun (s:String*):Unit = {

           s. Foreach (println(_))

       }

       fun ("hello", "a", "b","c")

 

/**

*5.匿名函数

* =>”就是匿名函数,多用于方法的参数是函数时,常用匿名函数

def funl (a:Int ,b:Int) :Int = {

      a+b

}

def fun: (Int, Int)=>Int = (a:Int,b:Int)=>{

       a+b

}

println(fun(100,200))

 

// *var funl: String => Uni t = (s:String) => {

         println(s)

}

fun l ("hello")

 

 

posted @ 2022-05-14 23:26  迟'  阅读(26)  评论(0)    收藏  举报