1. Apply与伴生对象
Apply简单理解可认为Apply为方法类默认方法的重载
val v=BigInt("12321")
实际调用代码是
def apply(x: String, radix: Int): BigInt =new BigInt(new BigInteger(x, radix))
另外一个例子写的很好就直接拿来用了
package com.robin.study /** * Created by robinmac on 15-7-22. */ class StudyApply { def testApply1(): Unit = { val v3 = BigInt("123121"); StudyApply.companion } def apply() = { println("Class's defined Apply") } def test { println("Class's defined test") } } object StudyApply{ var staticValue=1; def companion=println("I'm a companion"); def stat{ println("Companion's static method") } def apply() = { println("Companion's Apply") new StudyApply } var count = 0 def incc = { count += 1 } } object StudyApplyRunner extends App{ //类名后面跟方法名,调用的是伴生对象的方法 println("\n\nCalling Code: StudyApply.stat") StudyApply.stat //类名后面加括号,相当于调用伴生对象的apply方法 println("\n\nCalling Code: val a = StudyApply()") val a = StudyApply() //类的实例后面跟方法名,调用的时类中定义的方法 println("\n\nCalling Code: a.test") a.test //对象加括号相当于调用对象的apply方法 println("\n\nCalling Code: println(a())") println(a()) println("\n\nCalling Code: val b = StudyApply.apply()") val b = StudyApply.apply() println("b is :"+b) println("b.test is :"+b.test) println("a is :"+a.apply()) //半生对象的方法调用类似于类的静态方法调用 for(i <- 0 until 10){ StudyApply.incc } //半生对象的属性调用相当于类的属性方法调用 println(StudyApply.count) }
这个例子也很好的说明了伴生对象的用法。因为在Scala中没有静态方法,因此默认试用Class同名的Object中存储静态方法以及静态变量,并在类中进行使用。
根据个人当前理解,这应该仅仅是一个约定俗成,且这个同名对象被称为类的伴生对象。
2. 占位符 _与柯里化
class XiaHX { def twop(x:Int,y:Int)=x+y val twop2=((x:Int,y:Int)=>x+y).curried val cc=(twop _).curried; def add(x:Int,y:Int)=x+y val add3=add(3,_:Int) val add5=add(5,_:Int) } object XiaHX extends App { val m=new XiaHX(); val twopt=m.twop(1,_:Int); val twop33=m.twop2(1) println(twopt(1)) println(m.cc(1)(2)) println(m.twop2(1)(2)) println(twop33(4)) println(m.add5(3)); }
下划线可以理解为:对任意函数A,如果其某个输入k
参数为下划线,则其返回一个新的函数,新的函数的输入为k同类型变量,输出为A的输出。
其他很多东西都是这个定义的变形,但大多数都符合该规律。
例如上例子中定义了add,输入两个Int类型参数
def add(x:Int,y:Int)=x+y
val add3=add(3,_:Int)而后使add3成为add(3,_:Int)的结果,该函数实际返回的并不是X+Y的值,显然此时只有X被赋值为3,Y被下划线_替代了。所以其返回的是一个新的函数,该函数可认为是:
def add3(y:Int)=3+y