SCALA的例子详解

来源:互联网 发布:苹果手机延时摄影软件 编辑:程序博客网 时间:2024/05/17 04:18
scala是一门函数式的面向对象的语言,它运行在java虚拟机上。eg1、示例代码:scala>var helloWorld = "hello" + " world" println(helloWorld)scala>val again = " again" helloWorld = helloWorld + againprintln(helloWorld)输出:hello worldhello world againeg2、定义函数 def示例代码:def square(a: Int) = a * adef squareWithBlock(a: Int) = { a * a}val squareVal = (a: Int) => a * a (这里是将Int整数a映射为a*a的函数)def addOne(f: Int => Int, arg: Int) = f(arg) + 1(这里的=>表示所映射的类型,这就表示这个参数要是一个参数为int类型,返回的类型也是int 的方法)println("square(2):" + square(2))println("squareWithBlock(2):" + squareWithBlock(2))println("squareVal(2):" + squareVal(2))println("addOne(squareVal,2):" + addOne(squareVal, 2))输出结果:square(2):4squareWithBlock(2):4squareVal(2):4addOne(squareVal,2):5eg3、代码实例:import scala.reflect.io.Fileimport java.util.Scannerdef withScanner(f: File, op: Scanner => Unit) = {// 没有返回值的默认返回的是Unit    val scanner = new Scanner(f.bufferedReader)    try {        op(scanner)    } finally {        scanner.close()    }}withScanner(File("/proc/self/stat"),    scanner => println("pid is " + scanner.next()))其中widthScanner封装了try-Catch块,调用者不用再close了返回结果:pid is 6065eg4、定义类class Persion(val firstName: String, val lastName: String) {  //通过class定义类,val来定义字段,在类中def定义类中的函数,其中firstName和lastName会自动生成get,set方法    private var _age = 0    def age = _age  //这是一个方法    def age_=(newAge: Int) = _age = newAge    def fullName() = firstName + " " + lastName    override def toString() = fullName()//这是覆盖toString方法}val obama: Persion = new Persion("Barack", "Obama")//用new的方式创建类println("Persion: " + obama)println("firstName: " + obama.firstName)println("lastName: " + obama.lastName)obama.age_=(51)println("age: " + obama.age)返回结果:Persion: Barack ObamafirstName: BaracklastName: Obamaage: 51eg5、运行实例:def withClose(closeAble: { def close(): Unit }, //这里是将{def close():Unit}这个方法作为一种类型    op: { def close(): Unit } => Unit) {    try {        op(closeAble)    } finally {        closeAble.close()    }}class Connection {    def close() = println("close Connection")}val conn: Connection = new Connection()withClose(conn, conn =>    println("do something with Connection"))运行结果:do something with Connectionclose Connectioneg6、柯里化(currying)技术def add(x:Int, y:Int) = x + y是普通的函数def add(x:Int) = (y:Int) => x + y是柯里化后的函数,相当于返回一个匿名函数表达式。def add(x:Int)(y:Int) = x + y是简化写法
def withClose(closeAble: { def close(): Unit })//小白一枚,还是没有弄明白为什么我创建这个方法时候总是无效的???    (op: { def close(): Unit } => Unit) {    try {        op(closeAble)    } finally {        closeAble.close()    }}
class Connection {    def close() = println("close Connection")}val conn: Connection = new Connection()withClose(conn)(conn =>    println("do something with Connection"))
eg7、泛型
def withClose[A <: { def close(): Unit }, B](closeAble: A)//这里的A表示的是{def close():Unit}的子类型  (f: A => B): B =  try {    f(closeAble)  } finally {    closeAble.close()  }class Connection {  def close() = println("close Connection")}val conn: Connection = new Connection()val msg = withClose(conn) { conn =>  {    println("do something with Connection")    "123456"  }}println(msg)
返回结果:
do something with Connectionclose Connection123456
eg8 Traits 相当于java中的接口implements
trait ForEachAble[A] {  def iterator: java.util.Iterator[A]  def foreach(f: A => Unit) = {    val iter = iterator    while (iter.hasNext)      f(iter.next)  }}
trait JsonAble {  def toJson() =    scala.util.parsing.json.JSONFormat.defaultFormatter(this)}
val list = new java.util.ArrayList[Int]() with ForEachAble[Int] width JsonAble list.add(1); list.add(2)println("For each: "); list.foreach(x => println(x))//println("Json: " + list.toJson())


0 0
原创粉丝点击