版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chen18677338530/article/details/91450271
方法、函数、函数式编程、面向对象编程
函数式编程说明
基本语法
- 函数申明关键字是 def
- [参数:参数类型] 表示函数的输入,可以没有,如果有多个,可以用逗号分割
- 函数中的语句是为了实现某一功能的代码块
- 函数可以有返回值,也可以没有
- 如果没有 reture ,默认以执行到最后一行的结果作为返回值
object FunDemo1 { def main(args: Array[String]): Unit = { var n1 = 1 var n2 = 2 println("sum="+getSum(n1,n2,"+")) } def getSum(n1: Int, n2: Int,opt: String) = { if (opt == "+"){ n1 + n2 } else if (opt == "-"){ n1 - n2 } else { null } } }
斐波那契数列实现
object FunDemo2 { def main(args: Array[String]): Unit = { println(fbn(7)) } def fbn(i: Int) : Int = { if ( i == 1){ 1 } else if (i == 2){ 1 } else { (fbn(i - 2) + fbn(i - 1)) } } }
函数注意事项
object FunDemo3 { def main(args: Array[String]): Unit = { val tiger = new Tiger val tiger2 = test(10,tiger) println(tiger) println("-----") println(tiger2) println("-----") println(tiger.hashCode() + ":" + tiger2.hashCode()) } def test(i: Int, tig: Tiger) = { tig.name = "jack" tig } } class Tiger { var name:String = "" override def toString = s"Tiger(name=$name)" }
object FunDemo4 { def main(args: Array[String]): Unit = { def f1():Unit = { println("f1") } println("ok!") def sayOk() : Unit = { println("main sayOk") sayOk() def sayOk() :Unit = { println("sayok sayok") } } def sayNo():Unit = { println("main sayNo") } sayOk() } }
object FunDemo5 { def main(args: Array[String]): Unit = { test() def test(name:String = "jake") = { println(name) } } }
object FunDemo6 { def main(args: Array[String]): Unit = { mysqlCon(pwd="123456") } def mysqlCon(user: String = "admin", pwd: String = "123456"): Unit ={ println("user:"+user+",pwd:"+pwd) } }
过程
注意事项
惰性计算
惰性函数
object FunDemo7 { def main(args: Array[String]): Unit = { lazy val res = sum(10,20) println("-------------") println("-------------") println("-------------") println(res) } def sum(i: Int, i1: Int) :Int = { i + i1 } }
惰性函数注意事项
文章来源: https://blog.csdn.net/chen18677338530/article/details/91450271