该程序通过一段斐波那契数列的计算,比较一下Scala的函数式编程与java的面向对象的不同。
不多说了上代码。
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ // "_"符号相当于java的* 比如是java.util.* import scala.actors._ import scala.actors.Actor._ import scala.util.Random import java.util.Date object Actors{ def main(args: Array[String]){ val actors = new Array[Actor](250000) for(i <- 0 to 249999){ //actor循环,高并发模型 actors(i) = actor{ loop{ react{ case fibNum: Int => calculate(fibNum, i) } } } } val random = new Random() for(a <- actors){ a ! random.nextInt(25) } } //执行打印 def calculate(fibNum: Int, i: Int) = { val answer = fibonacci(fibNum) if((i + 1) % 1000 == 0){ val idPlusOne = i + 1 println("The " + fibNum + "th fibonacci number is " + answer + " (thread: " + idPlusOne + ")") } if((i + 1) % 250000 == 0){ System.exit(0) } } //斐波那契数列匹配,是不是比java定义同样的方法简单多了?连变量都不要了。 def fibonacci( n: Int): Int = n match { case 0 => 0 case 1 => 1 case _ => fibonacci(n -1) + fibonacci(n - 2) } }
再看看实现同样功能的java代码吧
import java.util.Date;
import java.util.Random;
public class JavaThreads extends Thread{
private static int THREAD_COUNT = 250000;
private int fibNum;
private int jid;
public JavaThreads(int id, int fibNum){
this.jid = id;
this.fibNum = fibNum;
}
public void run(){
int answer = fibonacci(fibNum);
if(this.jid % 1000 == 0){
System.out.println("The " + fibNum + "th fibonacci number is " + answer + " (thread: " + this.jid + ")");
}
}
private int fibonacci(int i){
if(i < 2){ return i;}
return fibonacci(i - 1) + fibonacci(i - 2);
}
public int getJid(){
return jid;
}
public void setJid(int jid){
this.jid = jid;
}
public int getFibNum(){
return fibNum;
}
public void setFibNum(int fibNum){
this.fibNum = fibNum;
}
public static void main(String args[]){
Date beginDate = new Date();
long memoryBegin = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
JavaThreads threads[] = new JavaThreads[THREAD_COUNT];
Random random = new Random();
for(int i = 0; i < THREAD_COUNT; i++){
threads[i] = new JavaThreads(i, random.nextInt(25));
}
for(JavaThreads thread : threads){
thread.start();
}
long memoryEnd = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Date endDate = new Date();
System.out.println("Completed in " + ((endDate.getTime() - beginDate.getTime())/1000) + " seconds");
System.out.println("Used memory: " + (memoryEnd - memoryBegin));
}
}
相信上面的java代码大家很熟悉了。该段demo其实展现了scala很多特性
比如:
1、object Actors {} 相当与 java的单例设计.没有过多的说明只是定义类的类型不一样,省去了java中构造私有的步骤达到同样的功能。
2、scala由于是基于JVM的,可以调用java类库. 代码中 import java.util.Date ;
3、val变量相当于java中的常量了(貌似是众多函数式编程语言的使用规范).var可以是变量,但用的少。
4、循环结构简洁、易于明白脱离了数组下标所带来的麻烦,for(i <- 0 to 249999).
5、actors高并发模型是借鉴Erlang,在公司的时候、服务器后台使用的比较多。
6、类型自动推测。把函数当返回值使用。
说实话,scala的特点真的蛮多的.特别是和java放在一起。相信你即使没有学过scala,只要有java基础一定看的出大概了。怎么样心动了么?