主要内容:
- 1、Scala的匹配模式(标准用法(match)/使用守卫/匹配类型)
- 2、Scala的case class,多用在匹配模式中
- 3、Scala中 :: 和 ::: 冒号的使用情况
- 4、Scala中 => 映射作用
一、Scala的匹配模式(标准用法(match)/使用守卫/匹配类型)
package DataStructureAndAlgorithm
/**
* Created by Administrator on 2017/12/23.
*/
object Test17ScalaMatch {
def main(args: Array[String]) {
val value = 3
// 标准用法(match)
val result = value match {
case 1 => "one"
case 2 => "two"
case _ => "other"
}
println("result of match is : " + result)
// 使用守卫
val result2 = value match {
case i if i ==1 => "one_1"
case i if i ==2 => "two_2"
case i if i ==3 => "other_2"
}
println("result of match is : " + result2)
// 匹配类型
def t(obj: Any) = obj match {
case x: Int => println("Int")
case s: String => println("String")
case _ => println("unknown type")
}
t(1)
t("a")
t(1L)
}
}
result of match is : other
result of match is : other_2
Int
String
unknown type
Process finished with exit code 0
二、case class 多用在模式匹配中
- case class 默认类型是: val
- 构造器中的每一个类型都是val, 不建议用var.
- 不用new就可以直接产生对象(为什么? apply方法)
package DataStructureAndAlgorithm
/**
* Created by Administrator on 2017/12/23.
*/
/*
case class 多用在模式匹配中
case class 默认类型是: val
构造器中的每一个类型都是val, 不建议用var.
不用new就可以直接产生对象(为什么? apply方法)
*/
case class Book(name: String, author: String)
object Test18ScalaCaseClass {
def main(args: Array[String]) {
val macTalk = Book("MacTalk", "CJQ")
macTalk match {
case Book(name, author) => println("this is a book")
case _ => println("unknown")
}
}
}
运行结果:
this is a book
Process finished with exit code 0
三、Scala中 :: 和 ::: 冒号的使用情况
def ::(x: B): List[B]
def :::(prefix: List[B]): List[B]
def ::(x: B): List[B]
Example:
1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)
中文解释就是 => 元素 :: 数组,表示在数组的首位添加元素
def :::(prefix: List[B]): List[B]
Example:
List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)
中文解释就是 => 数组1 ::: 数组2,表示在 数组2 的 首位 添加 数组1
四、Scala中 => 映射作用
var increase = (x: Int) => x + 1
increase(10)
res0: Int = 11