1.30
递归
递归就是方法自己调用自己
示例:求阶乘
object ClassDemo {
def f(n: Int): Int = if(n == 1) n else n * f(n - 1)
def main(args: Array[String]): Unit = {
println(f(5))
}
}
内存图解
Scala 中,内存分为五部分
栈
所有代码的执行、存储局部变量。
按照 FILO 的顺序执行,方法执行完毕后立马被回收。
堆
存储所有new 出来的对象。
在不确定的时间被垃圾收集器回收。
方法区
存储字节码文件,方法等数据。
程序执行完毕后,由操作系统回收资源。
本地方法区
和本地方法相关。
寄存器
和 CPU 相关。
斐波那契数列
已知数列1,1,2,3,5,8,13,求第12个数字。
object ClassDemo {
def f(n: Int): Int = {
if(n == 1 || n == 2)
1
else
f(n - 1) + f(n - 2)
}
def main(args: Array[String]): Unit = {
println(f(12))//144
}
}
案例:打印目录文件
定义 printFile 方法,该方法打印该文件夹下所有文件路径。
object ClassDemo {
def printFile(dir: File): Unit = {
if(!dir.isDirectory)
println("路径不合法")
else {
//获取该目录下所有文件及文件夹
val files:Array[File] = dir.listFiles()
for(listFile <- files){
if(listFile.isDirectory)
printFile(listFile)
else
println(listFile)
}
}
}
def main(args: Array[String]): Unit = {
printFile(new File("d:/"))
}
}

浙公网安备 33010602011771号