-Scala饰运行在Java虚拟机(Java Virtual Machine)之上,所以具备以下特色java
1) 轻松实现和丰富的Java类库互联互通程序员
2) 它既支持面向对象的编程方式,又支持函数式编程编程
3) 它写出的程序像动态语言同样简洁,但事实上它确是严格意义上的静态语言函数式编程
-先说下编程范式:函数
1) 在全部的编程范式中,面向对象编程(Object-Oriented Programming)无心是最大赢家测试
2) 但其实面向对象编程并非一种严格意义上的编程范式,严格意义上的编程范式分为:命令式编程(Imperative Programming)、函数式编程(Functional Programming)和逻辑式编程(Logic Programming)。面向对象编程只是上述几种范式的一个交叉产物,更多的仍是继承了命令式编程的基因scala
3) 在传统的语言设计中,只有命令式编程获得了强调,那就是程序员要告诉计算机应该怎么作。而递归则是经过灵巧的函数定义,告诉计算机作什么。所以在使用命令式编程思惟的程序中,是如今多数程序采用的编程方式,递归出镜的概率不多,而在函数式编程中,能够随处见到递归的方式设计
-Scala中循环不建议使用while和do...while,而建议使用递归orm
-计算1-100的和对象
import java.text.SimpleDateFormat import java.util.Date object boke_demo01 { def main(args: Array[String]): Unit = { //传统方法完成 1-100 的求和任务 val now: Date = new Date() val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val date = dateFormat.format(now) println("date=" + date) //输出时间 var res = BigInt(0) var num = BigInt(1) var maxVal = BigInt(100l) //BigInt(99999999l)[测试效率大数] while (num <= maxVal) { res += num num += 1 } println("res=" + res) //再一次输出时间 val now2: Date = new Date() val date2 = dateFormat.format(now2) println("date2=" + date2) //输出时间 } }
函数式编程的重要思想就是尽可能不要产生额外的影响,上面的案例代码就不符合函数式编程的思想,下面使用函数式编程方式来解决(Scala提倡的方式)
-案例演示
import java.text.SimpleDateFormat import java.util.Date object boke_demo01 { def main(args: Array[String]): Unit = { // 递归的方式来解决 //传统方法完成 1-100 的求和任务 val now: Date = new Date() val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val date = dateFormat.format(now) println("date=" + date) //输出时间 def mx(num: BigInt, sum: BigInt): BigInt = { if (num <= 100l) return mx(num + 1, sum + num) else return sum } //测试 var num = BigInt(1) var sum = BigInt(0) var res = mx(num, sum) println("res=" + res) //再一次输出时间 val now2: Date = new Date() val date2 = dateFormat.format(now2) println("date2=" + date2) //输出时间 } }
-求最大值
def max(xs: List[Int]): Int = { if (xs.isEmpty) throw new java.util.NoSuchElementException if (xs.size == 1) xs.head else if (xs.head > max(xs.tail)) xs.head else max(xs.tail) }
def reverse(xs: String): String = if (xs.length == 1) xs else reverse(xs.tail) + xs.head
def factorial(n: Int): Int = if (n == 0) 1 else n * factorial(n - 1)