# 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。