版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012848709/article/details/85015981
楔子
Scala函数简单学习
demo
package com.zhuzi
import java.util.Date
object Demo_Fun {
/**
* 1.方法定义
*
* 1.方法定义用def,函数的参数 要写类型,不写类型不可以。
* 2.函数的返回值类型可以不写,会自动推断
* 3.scala会将函数体中最后一行计算的结果当做返回值返回
* 4.可以写“return”,写了return要显式的声明方法体的放回类型。
* 5.定义方法时,如果不写“=”,那么无论方法体中最后一行计算的结果返回是什么,都会被丢弃,返回Unit
* 6.方法体可以一行搞定,那么方法体的“{... ...} ” 可以省略不写
*/
def max(x: Int, y: Int): Int = {
if (x > y) {
x
} else {
y
}
}
def max2(x: Int, y: Int) = if (x > y) x else y
/**
* 2. 递归函数
* 递归函数要显式的声明返回类型
*/
def fun(x: Int): Int = {
if (x == 1) {
1
} else {
x * fun(x - 1)
}
}
/**
* 3. 函数的参数有默认值
*
*/
def sum(x: Int = 100, y: Int = 200) = x + y
/**
* 4. 可变长的参数函数
*/
def funs(s: String*) = {
println("_" * 15)
s.foreach((ele: String) => {
println(ele)
})
}
/**
* 5.匿名函数
* 1."=>"就是匿名函数
* 2.匿名函数调用要赋值给一个变量,调用直接调用这个变量就可以
* 3.匿名函数不能显式的写函数返回类型
*/
val sum5: (Int, Int) => Int = (x: Int, y: Int) => {
x + y
}
/**
* 6.偏应用函数
*
* 偏应用函数是一个表达式,将方法中不变的参数写上,变化的参数使用“_”表示,下次直接调用这个偏应用表达式直接传入变化的参数就可以
*/
def showLog(date: Date, log: String) = {
println("date is " + date + ",log is " + log)
}
val date = new Date()
showLog(date, "a")
showLog(date, "b")
showLog(date, "c")
val fun = showLog(date, _: String)
fun("aaa")
fun("bbb")
fun("ccc")
/**
* 7.嵌套函数
*/
def fun7(x: Int) = {
def fun1(num: Int): Int = {
if (num == 1) {
1
} else {
num * fun1(num - 1)
}
}
fun1(x)
}
println(fun7(5))
def main(args: Array[String]): Unit = {
println(max(12, 5))
println(max2(12, 5))
println(fun(3))
println(sum())
//如果 是第二个参数传递值,直接写函数形参(应该可以这么理解)
println(sum(y = 20))
println(funs("hello", "zhuzi"))
}
}