今日学习:scala
主要是函数方面的知识
package com.chapter01.hanshu object Demo01 { def main(args: Array[String]): Unit = { //使用方法 val ha = new haha println(ha.sum(10,20)) //方法转函数 val f1 = ha.sum _ println("f1=" + f1) println("f1:" + f1(50,60)) //函数,求和 val f2 = (n1:Int,n2:Int) =>{ n1 + n2 } println("f2=" + f2) println("f2:" + f2(5,6)) } } class haha{ //方法 def sum(n1: Int, n2: Int): Int = { n1 + n2 } }
package com.chapter01.hanshu object FunDemo01 { def main(args: Array[String]): Unit = { val n1 = 30 val n2 = 20 val o = '-' println(getRes(n1, n2, o)) } //定义函数/方法 def getRes(n1: Int, n2: Int, oper: Char) = { //如果不写return,默认最后一个执行代码返回 if (oper == '+') { n1 + n2 } else if (oper == '-') { n1 - n2 } else { //返回null,若声明时写法为“: Int={}”直接写null不能与Int匹配,会报错 null } } }
package com.chapter01.hanshu object FunDemo02 { def main(args: Array[String]): Unit = { var tiger = new Tiger println(tiger.name) var tiger2 = test01(10, tiger) println(tiger2.name) //tiger的name发生改变,证明返回的是参数tiger println(tiger.name) } def test01(n1: Int, tiger: Tiger): Tiger = { println("n1=" + n1) tiger.name = "change" tiger } } class Tiger { var name = "start"
熟悉了一下递归的思路——栈的存储结构
package com.chapter01.hanshu object Demo02 { def main(args: Array[String]): Unit = { //输出为2,3,4。栈思想 test(4) } def test (n: Int): Unit ={ if(n > 2){ test(n - 1) } println("n=" + n) } }