1.前言
最近在参加Hadoop和Spark培训,需要使用Scala,自学了一下作为入门,这里作一个记录。
2.下载
1) 在scala官网下载,地址: http://www.scala-lang.org/
2) 下载IDE,地址: http://scala-ide.org/
3)配置环境变量
SCALA_HOME:C:\Program Files (x86)\scala
Path:C:\Program Files (x86)\scala\bin
在命令行中可以测试scala是否正常安装。
3.Hello Word
IDE 其实就是一个Eclipse的开发环境,大家都很熟悉了。新建工程->新建类即可!
可以发现,jre都是本地的,这也说明了scala是可以直接运行在JVM上的。scala也可以直接在交互式shell环境下运行(如命令行图所示),这也是scala很大的一个优势。
4.基本例子
1)变量的使用
object Hello { def main(args: Array[String]) {var 说明编译器可以做类型推断,字符和数字使用"+"连接成字符串。
var a = 1;
var b = 2;
var c = a + b;
println("c = " + c);
}
2)循环
var i = 0;// for loop execution with a rangefor( i <- 1 to 3){ println( "Value of i: " + i );}唯一的区别在于符号 <-
3) 集合
var index = 0;val numList = List(1,2,3,4,5,6); // for loop execution with a collection for( index <- numList ){ println( "Value of index: " + index );}4)函数
def printMe() : Unit = { println("Hello, Scala!")} def addInt( a:Int, b:Int ) : Int = { var sum:Int = 0 sum = a + b return sum }由参数和无参数的形式,感受一下!
5)调用同一个包下面的类
class Yiibai(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy println ("Yiibai x location : " + x); println ("Yiibai y location : " + y); }}在main函数里面调用:
val pt = new Yiibai(10, 20);pt.move(10, 10);6) Tuples
val pair = (99, "Luftballons")println(pair._1)println(pair._2)注意访问形式
7)类的继承
trait Friendly { def greet() = "Hi"}class Dog extends Friendly { override def greet() = "Woof"}class HungryDog extends Dog { override def greet() = "I'd like to eat my own dog food"}trait ExclamatoryGreeter extends Friendly { override def greet() = super.greet() + "!"}var pet: Friendly = new Dogprintln(pet.greet())pet = new HungryDogprintln(pet.greet())pet = new Dog with ExclamatoryGreeterprintln(pet.greet())pet = new HungryDog with ExclamatoryGreeterprintln(pet.greet())输出:
WoofI'd like to eat my own dog foodWoof!I'd like to eat my own dog food!8)Trait
类似Java interface, 但可以定义方法体!
trait Friendly { def greet() = "Hi"}class Dog extends Friendly { override def greet() = "Woof"}9)异常
import java.io.FileReaderimport java.io.FileNotFoundExceptionimport java.io.IOExceptionobject Test { def main(args: Array[String]) { try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException =>{ println("Missing file exception") } case ex: IOException => { println("IO Exception") } } }}输出:
C:/>scalac Test.scalaC:/>scala TestMissing file exceptionC:/>10)文件
写文件
import java.io._object Test { def main(args: Array[String]) { val writer = new PrintWriter(new File("test.txt" )) writer.write("Hello Scala") writer.close() }}读文件
import scala.io._Source.fromFile(new java.io.File("cn.scala")).getLines().foreach(println)5.总结
scala 在大数据,云计算方面有较为广泛的运用,学习一下还是挺有用的,欢迎大家一起分享讨论。