七周七语言之Scala

# Hello world
# hello.scala
def helloworld {
  println("Hello world!")
}
helloworld
实际操作效果:


#实现Compass罗盘功能
class Compass() {
  val directions = List("north", "east", "south")
  var bearing = 0
  print("Initial bearing: ")
  println(direction)

  def direction() {
    directions(bearing)
  }

  def inform(turnDirection: String) {
    println("Turning" + turnDirection + ". Now bearing " + direction)
  }

  def turnRight() {
    bearing = (bearing + 1) % directions.size
    inform("right")
  }

  def turnLeft() {
    bearing = (bearing + (directions.size -1)) % directions.size
    inform("left")
  }
}

val myCompass = new Compass
myCompass.turnRight
myCompass.turnRight
myCompass.turnLeft
myCompass.turnLeft
myCompass.turnLeft
myCompass.turnLeft

#使用Employee类扩展Person类
class Person(val name: String) {
  def talk(message: String) = println(name + " says " + message)
  def id(): String = name
}

class Employee(override val name: String, val number: Int) extends Person(name) {
  override def talk(message: String) {
    println(name + " with number " + number + " says " + message)
  }
  override def id():String = number.toString
}
val employee = new Employee("Yoda", 4)
employee.talk("Extend or extend not. There is no try.")


# 并发,获取从一些网站发送响应的字节大小
import scala.io._ 
import scala.actors._ 
import Actor._ 

object PageLoader { 
def getPageSize(url : String) = Source.fromURL(url)(io.Codec("UTF-8")).mkString.length 
} 

var urls = List("http://www.baidu.com/","http://www.sina.com/","http://www.bing.com","http://www.cnn.com/") 

def timeMethod(method: () => Unit) = { 
val start = System.nanoTime 
method() 
val end = System.nanoTime 
println("Method took " + (end - start)/1000000000.0 + " seconds.") 
} 

def getPageSizeSequentially() = { 
for(url <- urls) { 
println(url) 
println("Size for " + url + ": " + PageLoader.getPageSize(url)) 
} 
} 

def getPageSizeConcurrently() = { 
val caller = self 

for(url <- urls) { 
actor { caller ! (url, PageLoader.getPageSize(url)) } 
} 

for(i <- 1 to urls.size) { 
receive { 
case (url, size) => println("Size for " + url + ": " + size) 
} 
} 
} 

println("Sequential run:") 
timeMethod { getPageSizeSequentially } 
println("Concurrent run:") 
timeMethod { getPageSizeConcurrently }

优势:
1.并发:actor模型和线程池都是很受欢迎的,并且无需可变状态的并发应用设计能力也绝对是一个巨大的进步。
2.遗留Java的演化:Scala应用可以直接使用Java库,并且必要时还可以使用代理对象(proxy object)的代码生成功能,与Java的互操作性非常好。
3.领域特定语言:灵活的语法和操作符重载,再加上mixin,很方便创建DSL。
4.XML:Scala可以很好的支持XML的读取。
5.桥接:可以很好的桥接Java与函数式编程模型。

不足:
1.静态类型:静态类型对于函数式编程语言来说是很友好的,但是对于面向对象编程语言来说可能是负担。
2.语法:语法上不太友好,与Java有些不同。
3.可变性:可变性可能导致各种各样的并发bug。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值