元组最多支持22个元素
元组可以new 也可以不new,甚至可以直接写()中写元素
package com.bjsxt.scala
object Lesson_Tuple {
def main(args: Array[String]): Unit = {
val tuple1: Tuple1[String] = new Tuple1("hello")
val tuple2: (String, Int) = new Tuple2("a", 100)
val tuple3: (Int, Boolean, String) = new Tuple3(1, true, "C")
val tuple4: (Int, Double, String, Boolean) = Tuple4(1, 3.4, "abc", false)
val tuple6: (Int, Int, Int, Int, Int, String) = (1, 2, 3, 4, 5, "abc")
val tuple22 = (1,2,3,4,5,6,7,8,9,10,11,12,"abc",14,15,16,17,18,19,20,21,22)
val value:String = tuple22._13
val iter: Iterator[Any] = tuple6.productIterator
iter.foreach(println)
}
}
一个类继承多个trait时,第一个关键字使用 extents,之后使用with
Trait中可以有方法体的实现或者方法体的不实现,类继承了Trait要实现Trait中没有实现的方法
package com.bjsxt.scala
trait Rad{
def read(name:String)={
println(s"$name is reading...")
}
}
trait Listen{
def listen(name:String)={
println(s"$name is listening...")
}
}
class Human extends Rad with Listen {
}
object Lesson_Trait1 {
def main(args: Array[String]): Unit = {
val h = new Human()
h.read("wdt")
h.listen("nm")
}
}
Match 模式匹配
1.case _ 什么都匹配不上匹配,放在最后
2.match 可以匹配值还可以匹配类型
3.匹配的过程中会有数值的转换
4.从上往下匹配,匹配上之后会自动终止
5.模式匹配外部的“{..}”可以省略
偏函数,只能匹配一个值,匹配上了返回某个值
PartialFunction[A,B] A是匹配的类型,B是匹配上返回的类型
package com.bjsxt.scala
object Lesson_Match {
def main(args: Array[String]): Unit = {
val ty = (1,1.2,"abc",'a',true)
val iter:Iterator[Any] = tp.productIterator
iter.foreach(MatchTest)
}
def MatchTest(o:Any)={
o match {
case 1=>println("value is 1")
case i:Int=>println(s"type is int ,value = $i")
case d:Double=>println(s"type is Double ,value = $d")
case s:String=>println(s"type is String ,value = $s")
case 'a'=>println("value is c")
case _=>{println("no match..")}
}
}
}