函数 必须给出参数类型,可是不必定给出函数的返回值类型,只要右侧函数体不包含递归语句,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