case class(多用在模式匹配中)
构造器中的每一个类型都为val,不建议用var
不用new就可以直接产生对象(为什么?apply方法)
case class Book(name:String, author:String)
object Basic5 {
def main(args:Array[String]): Unit ={
val macTalk = Book("MacTalk", "CJQ")
macTalk match{
case Book(name, author) => println("this is book")
case _ => println("unknown")
}
}
}
输出结果:

集合操作
集合:List,Set,Tuple,Map

foreach, map,filter, zip, partition(列表分割), flatten(扁平化), flatmap(map + flatten),sorted
foreach:


map:

filter:

zip:

partition:

flatten:

flatMap:先做map,然后flatten

sorted:

隐式转换
位于源目标类型的伴生对象中的隐式函数
位于当前作用域可以以单个标识符指代的隐式函数
object Basic6 {
def main(args:Array[String]): Unit ={
implicit def a2RichA(a:A) = new RichA(a)
val a = new A
a.rich
}
}
class A{
}
class RichA(a:A){
def rich: Unit ={
println("rich...")
}
}
输出结果:

隐式参数
object Basic6 {
def main(args:Array[String]): Unit ={
implicit val name = "implicit!!!"
testParam
testParam("xxx")
}
def testParam(implicit name :String): Unit ={
println(name)
}
}
输出结果:

隐式类
object Basic6 {
implicit class Calculator(x:Int){
def add(a:Int):Int = a + 1
}
println(1.add(1))
}
输出结果:

本文深入介绍了Scala中的case class用法,包括其模式匹配能力,无需new即可创建对象的特性。此外,还探讨了集合操作如foreach、map、filter、zip、partition和flatten等,并展示了隐式转换的概念,包括如何定义隐式函数、隐式参数和隐式类。通过实例展示了隐式转换的应用。
786

被折叠的 条评论
为什么被折叠?



