AnonymousFunc类如下所示:
package com.test.app
object AnonymousFunc {
def adder(m: Int, n: Int) = m + n //更简单的写法
def hello(x: Int) = x + 1 //简单的写法
val add2 = adder(2, _: Int) //_表示占位符
def multiply(m: Int)(n: Int): Int = m * n //优雅的写法
def main(args: Array[String]) {
println(add2(3))
println(multiply(2)(3))
val timesTwo = multiply(2)(_)
println(timesTwo(3))
var brand: String = "HP" //命名规则类似于JAVA
val color: String = if (brand == "TI") {
"blue"
} else if (brand == "HP") {
"black"
} else {
"white"
}
println(color);
}
}
PrintlnTest:
package com.test.app
object PrintlnTest {
def main(args: Array[String]) {
val array = Array(0, 1, 2, 3, 4, 5)
array.foreach(i => print(i))
println()
array.foreach(print(_))
println()
array.foreach(print)
println()
for (i <- 0 until 5) {
print(i)
}
println()
for (i <- 0 to 5) {
print(i)
}
println()
val map = Map(0 -> 0, 1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4, 5 -> 5)
map.foreach {
case (key, value) => {
println("key:" + key + " value:" + value)
}
}
val array1 = Array(0, 1, 2, 3, 4, 5)
val array2 = Array(6, 7, 8, 9)
val array3 = array1 ++ array2
/**
* drop(n) 移除前n个元素
* take(n) 获取前n个元素
* filter(condition) 获取指定condition的元素
*/
//array3.foreach(println)
array3.take(3).foreach(println)
// array3.drop(1).foreach(println)
// array3.filter(_ != 1).foreach(println)
/**
* += 添加元素
* ++ 合并集合
*/
}
}
HelloScala:
package com.test.app
object HelloScala {
def main(args: Array[String]) {
//前10个数
var i = 0;
val rt =
for (
e <- ('a' to 'z') if { i = i + 1; i <= 10 }
) printf("%d:\t%s\n", i, e)
//或者如下:
('a' to 'z').slice(0,10).foreach(println)
//1 to 100 和小于1000的数
var (n,sum)=(0,0);
for(i<-0 to 100 if (sum+i<1000)) { n=i; sum+=i }
}
}
ScalaObject:
package com.test.app
object ScalaObject {
//Map
val colors = Map("red" -> 0xFF0000,
"turquoise" -> 0x00FFFF,
"black" -> 0x000000,
"orange" -> 0xFF8040,
"brown" -> 0x804000)
//match case: 相当于swich case
def main(args: Array[String]) {
println("Hello, world! " + args.toList)
for (name <- args) println(
colors.get(name) match {
case Some(code) =>
name + " has code: " + code
case None =>
"Unknown color: " + name
})
colors.get("red")
}
}