码迷,mamicode.com
首页 > 其他好文 > 详细

scala学习小记3

时间:2015-04-25 14:57:58      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

模式匹配

• 标准用法(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))
 

scala学习小记3

标签:

原文地址:http://www.cnblogs.com/mlj5288/p/4455852.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!