1 方法的访问域
private[this] The method is available only to the current instance of the class it’s declared in.
private The method is available to the current instance and other instances of the class it’s declared in.
protected The method is available only to instances of the current class and subclasses of the current class.
private[model] The method is available to all classes beneath the com.acme.coolapp.modelpackage.
private[coolapp] The method is available to all classes beneath the com.acme.coolapppackage.
private[acme] The method is available to all classes beneath the com.acmepackage.
(no modifier) The method is public
2 var f5:(Int)=>Int = (x:Int)=>x+3
结果:f5: Int => Int = <function1>
分析:
2.1 定义匿名函数 (x:Int)=>x+3
2.2 把匿名函数赋给变量f5 var f5 = (x:Int)=>x+3
2.3 定义函数 def m(x:Int)=x+3
2.4 把函数m赋给变量f4 var f4 = m _ 或 var f4 :(Int)=>Int = m
2.5 根据把函数赋给f4的表达式 var f4:(Int)=>Int = m 对2.2 的变量f5做扩展为:var f5:(Int)=>Int = (x:Int)=>x+3
解释:把匿名函数(x:Int)=>x+3 赋值给以函数(参数为Int类型,返回值为Int的函数)为参数的f5
3 闭包
闭包名称源自于通过“捕获”自由变量的绑定,从而对函数字面量执行的“关闭”行动
函数值是关闭这个开放项(x:Int) => x + more行动的最终产物,因此被称为闭包
4 def echo(args:String*){args.foreach(println(_))}
var arr = Array("1","2","3")
echo(arr:_*)
5 尾递归
最后一个动作调用自己的函数,被称为尾递归
尾调用优化限定了方法或嵌套函数必须在最后一个操作调用本身,而不是转到某个函数值或什么其他的中间函数的情况
def boom(x:Int):Int = {
if(x == 0) throw new Exception("boom!")
else boom(x - 1) + 1
} 不是尾递归,因为最后一个动作执行的是 递增操作
def boom(x:Int):Int = {
if(x == 0) throw new Exception("boom!")
else boom(x - 1)
}这个是尾递归
6 val c = scala.math.cos _ (注意空格)
val c = scala.math.cos(_)
对于两个参数:
val p = scala.math.pow _ (注意空格)
val p = scala.math.pow(_, _)
7 val sayHello = () => println("Hello")
def executeFun(callBack:()=>Unit){callBack()}
val fun:(()=>Unit)=>Unit=executeFun _
val fun01:(()=>Unit)=>Unit={executeFun }
8 Partially Applied Functions
val sum = (a:Int , b:Int ,c:Int)=>a+b+c
val f = sum(1,2,_:Int)
f(3)
9 Creating a Function that returns a Function
def saySomething(prefix:String) = (s:String) => println(prefix + "," +s)
val a=saySomething("a")
a("b")
def greeting(language:String) = (name:String)=>{
language match{
case "english"=> println("Hi," + name)
case "spanish" => println("Buenos dias, " + name)
}
}
val a01 = greeting("spanish")
a01("kuoo3942")
10 To use distinctwith your own class, you’ll need to implement the equalsand hashCode
methods
class Person(firstName: String, lastName: String) {
override def toString = s"$firstName $lastName"
def canEqual(a: Any) = a.isInstanceOf[Person]
override def equals(that: Any): Boolean =
that match {
case that: Person => that.canEqual(this) && this.hashCode == that.hashCode
case _ => false
}
override def hashCode: Int = {
val prime = 31
var result = 1
result = prime * result + lastName.hashCode;
result = prime * result + (if (firstName == null) 0 else firstName.hashCode)
return result
}
}
object Person {
def apply(firstName: String, lastName: String) =
new Person(firstName, lastName)
}
val dale1 = new Person("Dale", "Cooper")
val dale2 = new Person("Dale", "Cooper")
val ed = new Person("Ed", "Hurley")
val list = List(dale1, dale2, ed)
val uniques = list.distinct
11
class Person (var name: String) extends Ordered [Person]
{
override def toString = name
// return 0 if the same, negative if this < that, positive if this > that
def compare (that: Person) = {
if (this.name == that.name)
0
else if (this.name > that.name)
1
else
−1
}
}
def compare (that: Person) = this.name.compare(that.name)
12 Converting a Collection to a String with mkString
13 val fruits = Array("cherry", "apple", "banana")
fruits: Array[String] = Array(cherry, apple, banana)
scala.util.Sorting.quickSort(fruits) //对Array进行排序
14 Map
val states = Map("AL" -> "Alabama", "AK" -> "Alaska")
15 val Array(month, revenue, expenses, profit) = line.split(",").map(_.trim)
println(s"$month $revenue $expenses $profit")
16 def getListOfFiles(dir: File, extensions: List[String]): List[File] =
{
dir.listFiles.filter(_.isFile).toList.filter{ file =>extensions.exists(file.getName.endsWith(_))}
}
17 执行外部命令:import sys.process._
"ls -al".!
total 64
drwxr-xr-x 10 Al staff 340 May 18 18:00 .
drwxr-xr-x 3 Al staff 102 Apr 4 17:58 ..
-rw-r--r-- 1 Al staff 118 May 17 08:34 Foo.sh
-rw-r--r-- 1 Al staff 2727 May 17 08:34 Foo.sh.jar
res0: Int = 0
val exitCode = "ls -al".!
println(exitCode)
结果:0
注释:
Use the !method to execute the command and get its exit status.
Use the !!method to execute the command and get its output.
Use the linesmethod to execute the command in the background and get its result as a Stream.
18 集合
18.1 Array
18.2 List
18.3 ArrayBuffer
18.4 ListBuffer
18.5 Queue
18.6 Stack
18.7 Set
18.8 Map
18.9 toList() toArray()
18.10 Tuples
19 sealed修饰符
19.1 其修饰的trait,class只能在当前文件里面被继承
private[this] The method is available only to the current instance of the class it’s declared in.
private The method is available to the current instance and other instances of the class it’s declared in.
protected The method is available only to instances of the current class and subclasses of the current class.
private[model] The method is available to all classes beneath the com.acme.coolapp.modelpackage.
private[coolapp] The method is available to all classes beneath the com.acme.coolapppackage.
private[acme] The method is available to all classes beneath the com.acmepackage.
(no modifier) The method is public
2 var f5:(Int)=>Int = (x:Int)=>x+3
结果:f5: Int => Int = <function1>
分析:
2.1 定义匿名函数 (x:Int)=>x+3
2.2 把匿名函数赋给变量f5 var f5 = (x:Int)=>x+3
2.3 定义函数 def m(x:Int)=x+3
2.4 把函数m赋给变量f4 var f4 = m _ 或 var f4 :(Int)=>Int = m
2.5 根据把函数赋给f4的表达式 var f4:(Int)=>Int = m 对2.2 的变量f5做扩展为:var f5:(Int)=>Int = (x:Int)=>x+3
解释:把匿名函数(x:Int)=>x+3 赋值给以函数(参数为Int类型,返回值为Int的函数)为参数的f5
3 闭包
闭包名称源自于通过“捕获”自由变量的绑定,从而对函数字面量执行的“关闭”行动
函数值是关闭这个开放项(x:Int) => x + more行动的最终产物,因此被称为闭包
4 def echo(args:String*){args.foreach(println(_))}
var arr = Array("1","2","3")
echo(arr:_*)
5 尾递归
最后一个动作调用自己的函数,被称为尾递归
尾调用优化限定了方法或嵌套函数必须在最后一个操作调用本身,而不是转到某个函数值或什么其他的中间函数的情况
def boom(x:Int):Int = {
if(x == 0) throw new Exception("boom!")
else boom(x - 1) + 1
} 不是尾递归,因为最后一个动作执行的是 递增操作
def boom(x:Int):Int = {
if(x == 0) throw new Exception("boom!")
else boom(x - 1)
}这个是尾递归
6 val c = scala.math.cos _ (注意空格)
val c = scala.math.cos(_)
对于两个参数:
val p = scala.math.pow _ (注意空格)
val p = scala.math.pow(_, _)
7 val sayHello = () => println("Hello")
def executeFun(callBack:()=>Unit){callBack()}
val fun:(()=>Unit)=>Unit=executeFun _
val fun01:(()=>Unit)=>Unit={executeFun }
8 Partially Applied Functions
val sum = (a:Int , b:Int ,c:Int)=>a+b+c
val f = sum(1,2,_:Int)
f(3)
9 Creating a Function that returns a Function
def saySomething(prefix:String) = (s:String) => println(prefix + "," +s)
val a=saySomething("a")
a("b")
def greeting(language:String) = (name:String)=>{
language match{
case "english"=> println("Hi," + name)
case "spanish" => println("Buenos dias, " + name)
}
}
val a01 = greeting("spanish")
a01("kuoo3942")
10 To use distinctwith your own class, you’ll need to implement the equalsand hashCode
methods
class Person(firstName: String, lastName: String) {
override def toString = s"$firstName $lastName"
def canEqual(a: Any) = a.isInstanceOf[Person]
override def equals(that: Any): Boolean =
that match {
case that: Person => that.canEqual(this) && this.hashCode == that.hashCode
case _ => false
}
override def hashCode: Int = {
val prime = 31
var result = 1
result = prime * result + lastName.hashCode;
result = prime * result + (if (firstName == null) 0 else firstName.hashCode)
return result
}
}
object Person {
def apply(firstName: String, lastName: String) =
new Person(firstName, lastName)
}
val dale1 = new Person("Dale", "Cooper")
val dale2 = new Person("Dale", "Cooper")
val ed = new Person("Ed", "Hurley")
val list = List(dale1, dale2, ed)
val uniques = list.distinct
11
class Person (var name: String) extends Ordered [Person]
{
override def toString = name
// return 0 if the same, negative if this < that, positive if this > that
def compare (that: Person) = {
if (this.name == that.name)
0
else if (this.name > that.name)
1
else
−1
}
}
def compare (that: Person) = this.name.compare(that.name)
12 Converting a Collection to a String with mkString
13 val fruits = Array("cherry", "apple", "banana")
fruits: Array[String] = Array(cherry, apple, banana)
scala.util.Sorting.quickSort(fruits) //对Array进行排序
14 Map
val states = Map("AL" -> "Alabama", "AK" -> "Alaska")
15 val Array(month, revenue, expenses, profit) = line.split(",").map(_.trim)
println(s"$month $revenue $expenses $profit")
16 def getListOfFiles(dir: File, extensions: List[String]): List[File] =
{
dir.listFiles.filter(_.isFile).toList.filter{ file =>extensions.exists(file.getName.endsWith(_))}
}
17 执行外部命令:import sys.process._
"ls -al".!
total 64
drwxr-xr-x 10 Al staff 340 May 18 18:00 .
drwxr-xr-x 3 Al staff 102 Apr 4 17:58 ..
-rw-r--r-- 1 Al staff 118 May 17 08:34 Foo.sh
-rw-r--r-- 1 Al staff 2727 May 17 08:34 Foo.sh.jar
res0: Int = 0
val exitCode = "ls -al".!
println(exitCode)
结果:0
注释:
Use the !method to execute the command and get its exit status.
Use the !!method to execute the command and get its output.
Use the linesmethod to execute the command in the background and get its result as a Stream.
18 集合
18.1 Array
18.2 List
18.3 ArrayBuffer
18.4 ListBuffer
18.5 Queue
18.6 Stack
18.7 Set
18.8 Map
18.9 toList() toArray()
18.10 Tuples
19 sealed修饰符
19.1 其修饰的trait,class只能在当前文件里面被继承
19.2 用sealed修饰这样做的目的是告诉scala编译器在检查模式匹配的时候,让scala知道这些case的所有情况,scala就能够在编译的时候进行检查,看你写的代码是否有没有漏掉什么没case到,减少编程的错误
20 Execute Around Method模式
def writeToFile(filename:String)(codeBlock:PrintWriter=>Unit)={
val writer = new PrintWriter(new File(filename))
try{codeBlock(writer)} finally{writer.close()}
}
writeToFile("output.txt"){writer=>writer.write("hell from scala")}