scala学习小记3

模式匹配

• 标准用法(match)

var value=1
var res= value match {
case 1 => "one"
case 2 =>"two"
case _ =>"some other"
}
println(res)

•使用守卫(if)

var res2= value match {
case i if i==1 => "one"
case i if i==2 =>"two"
case _ =>"some other"
}
println(res2)


•匹配类型

def t(obj:Any)=obj match {
case i:Int => println("int")
case s:String =>println("string")
case _ =>println("others")
}
t(1)
----------------
case class Book(name:String,author:String)//case class(多用在模式匹配中)构造器中的每一个类型都为val, 不建议用var。不用new就可以直接产生对象(为什么?apply方法)
val book=Book("spark","mlj")
book match {
case Book(name,author) => println("a book")
case _ =>println("other type")
}
-----------------------------------------------------------
高阶函数






-----------------------------------------------------
隐式

隐式转换

• 位于源目标类型的伴生对象(object)中的隐式函数
• 位于当前作用域可以以单个标识符指代的隐式函数

class  A{

}
class richA(a:A){
def rich: Unit ={
println("rich....")
}
}
使用:
implicit def a2richA(a:A)=new richA(a)
val a=new A
a.rich()
def testParam(implicit name:String): Unit ={
println(name)
}   

隐式参数

   implicit val name="implicit"

  testParam//free of conveying parameters
testParam("sssss")

隐式类(Scala 2.10)

implicit class cal(x:Int){
    def add(a:Int)=a+1
}
println(3.add(1))
 
posted @ 2015-04-25 13:51  孟想阳光  阅读(140)  评论(0)    收藏  举报