scala函數

函數 必須給出參數類型,可是不必定給出函數的返回值類型,只要右側函數體不包含遞歸語句,Scala就能夠本身推斷返回值類型
def 函數名(參數名:類型,參數名1:類型2):返回類型 = {}

explame:

def sayHello(name:String,age:Int) = { 
    print("name: "+name + " age: "+age)
}
:paste/** 多行函數用{}包含函數體 **/
def sayHello(name:String,age:Int) = { 
    if(age > 18){
        println("name: "+name + " age: "+age + " i am a audlt \n")
        age/** if是有返回值的 這裏是age **/
    }else{
        println("name: "+name + " age: "+age + " i am a boy \n")
        age/** if是有返回值的 這裏是age **/
    }
}
/** 單行函數 **/
scala> def sayHello(name:String) = println("hello " + name)
sayHello: (name: String)Unit

scala> sayHello("xp")
hello xp
/** 函數賦值給變量 **/
scala> def sayHello(name:String) = println("hello" + name)
sayHello: (name: String)Unit


scala> val sayHelloFun = sayHello _
sayHelloFun: String => Unit = <function1>

scala> sayHello
sayHello      sayHelloFun   

scala> sayHelloFun("xp")
helloxp
/** 匿名函數賦值給變量 **/
/** val 變量 = 參數列表 => 函數體 **/
scala> val sayHello = (name:String) => print("hello" + name)
sayHello: String => Unit = <function1>

scala> sayHello
sayHello      sayHelloFun   

scala> sayHello("DD")
helloDD
scala> val sayHello = (name:String) => print("hello" + name)
sayHello: String => Unit = <function1>

/** 高階函數 **/
scala> def greeting(func:(String) => Unit,name:String) {func(name)}
greeting: (func: String => Unit, name: String)Unit

scala> greeting(sayHelloFun,"CC")
helloCC
/** 高階函數返回函數 **/
scala> def greeting(name:String) = (name:String) => println("hello "+name)
greeting: (name: String)String => Unit

scala> val greet = greeting("hello")
greet: String => Unit = <function1>

scala> greet("xp")
hello xp
相關文章
相關標籤/搜索