本文的假设基础是:你有一定的编程功底,并且已经知道你要使用Scala做什么。最好对函数式编程有所了解。如果你有脚本语言的基础例如Python,那么一定会更快。
和其他脚本语言相通,Scala也有一个解释器。
val msg="shitshit"
var h="hhhhh"
h="fffff"
def max(x:Int,y:Int): Int=if(xelse x
也可以不声明返回类型:
def max2(x: Int, y: Int) = if (x < y) y else x
可以使用括号括起来:
scala> def max3(x: Int, y: Int) = { if (x < y) y else x }
调用方法没有什么特殊之处:
max(1,2)
在系统终端中
scala my.scala
scala可以方便地调用外部参数:
#打印出第一个参数
println(arg(0))
linux下的一点奇技淫巧:
#!/bin/sh
exec scala $0 $@
!#
// Say hello to the first argument
println("Hello, " + args(0) + "!")
./helloarg globe
var i = 0
while (i < args.length) {
if (i != 0)
print(" ")
print(args(i))
i += 1
}
println()
foreach
args.foreach(arg=>println(arg))
for
for(arg<-args)
println(arg)
这是一个比较奇怪的定义方式:
val greetStrings = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"
for (i <- 0 to 2)
print(greetStrings(i))
其中
greetStrings(0) = "Hello"
会被偷偷换成
greetStrings.update(0, "Hello")
list的定义和串联
val oneTwoThree = List(1, 2, 3)
val fourfive=List(4,5)
val s=oneTwoThree:::fourfive
和元素串联:
val m=oneTwoThree::1
tuple
方便的结构体
val pair =(100,"shit")
println(pair._1)
println(pair._2)
HashSet
import scala.collection.mutable.HashSet
val jetSet = new HashSet[String]
jetSet += "Lear"
jetSet += ("Boeing", "Airbus")
println(jetSet.contains("Cessna"))
HashMaps
import scala.collection.mutable.HashMap
val treasureMap = new HashMap[Int, String]
treasureMap += 1 -> "Go to island."
treasureMap += 2 -> "Find big X on ground."
treasureMap += 3 -> "Dig."
println(treasureMap(2))
// In greetSimply.scala
class SimpleGreeter {
val greeting = "Hello, world!"
def greet() = println(greeting)
}
val g = new SimpleGreeter
g.greet()
// In greetFancily.scala
class FancyGreeter(greeting: String) {
def greet() = println(greeting)
}
val g = new FancyGreeter("Salutations, world")
g.greet
这个类看起来有点奇怪,定义也是构造函数。
单例模式
// In WorldlyGreeter.scala
// The WorldlyGreeter class
class WorldlyGreeter(greeting: String) {
def greet() = {
val worldlyGreeting = WorldlyGreeter.worldify(greeting)
println(worldlyGreeting)
}
}
// The WorldlyGreeter companion object
object WorldlyGreeter {
def worldify(s: String) = s + ", world!"
}
因为Scala下是面向对象的,所以其入口函数也在类里:
// In WorldlyApp.scala
// A singleton object with a main method that allows
// this singleton object to be run as an application
object WorldlyApp {
def main(args: Array[String]) {
val wg = new WorldlyGreeter("Hello")
wg.greet()
}
}
traits类似于java中的interface
trait Friendly {
def greet() = "Hi"
}
连关键字都没有改:extentds、override
class Dog extends Friendly {
override def greet() = "Woof"
}