Object内部的方法,我们可以直接通过Object.method,需要使用哪个方法就用哪个,类似于java里的static。
package scala
object Timer {
var count = 0
def increment():Long = {
count += 1
count
}
}
放到scala命令行执行会发现,这个方法操作类似于单例,每次调用都会累加起来。
scala> object Timer {
|
| var count = 0
| def increment():Long = {
|
| count += 1
| count
|
| }
|
| }
defined object Timer
scala> Timer.increment
res0: Long = 1
scala> Timer.increment
res1: Long = 2
scala> Timer.increment
res2: Long = 3
伴生对象vs伴生类
例如:
class A
Object A
那么 class A就叫做 object A的伴生类,object A就叫做class A的伴生对象
类名() ==> Object.apply(){
//表面上是没有使用new的,但是底层肯定是用了new的
……
new Class
}
对象/引用() ==> Class.apply ,也就是new 出来的类
package scala
object ApplyDemo {
def main(args: Array[String]): Unit = {
// for (i <- 1 to 10) {
// ApplyTest.increment
//
// }
//
// println(ApplyTest.count)
// ApplyTest.static
// val a = new ApplyTest()
// println(a)
// a.method()
//现在没有new,直接类名()==> Object对象里面的apply方法
// val b = ApplyTest()
// b.method()
val c = new ApplyTest()
println(c)
println(c()) //c是一个引用,c()调用的是Class的apply方法,不常用
val array = Array("a","b","c")
}
}
class ApplyTest {
def method() : Unit = {
println("class ApplyTest method")
}
def apply() = {
"class apply method invoke"
}
}
object ApplyTest {
println("object ApplyTest enter...")
var count = 0
def increment = {
count = count + 1
count
}
def static : Unit={
println("object ApplyTest static")
}
def apply() = {
println("class apply method invoke")
new ApplyTest()
}
println("object ApplyTest leave...")
}
1.函数赋值给变量
函数赋值给变量需要使用空格+_
package scala
object FunctionAdApp {
def main(args: Array[String]): Unit = {
//函数赋值给变量使用空格+_
val sayHelloFunc = sayHello _
}
def sayHello(name:String) : Unit = {
println("Hello" + name)
}
}
2.匿名函数
(参数名:参数类型) => 函数体
val m = {x:Int => x+1}
(x:Int) => x+1
def add = (x:Int,y:Int) => {x+y}
3.函数的curying(科里化)
sum(x:Int,y:Int)
package scala
object FunctionAdApp {
def main(args: Array[String]): Unit = {
//函数赋值给变量使用空格+_
val sayHelloFunc = sayHello _
println(sum(1,2))
println(add(3)(4))
}
def sayHello(name:String) : Unit = {
println("Hello" + name)
}
def sum(x:Int,y:Int) = {x + y}
def add(x:Int)(y:Int) = {x + y}
}
偷偷摸摸的为一个类的方法进行增强
Man => Superman
java中可以用代理实现
Java proxy
package scala
object ImlicitApp {
def main(args: Array[String]): Unit = {
implicit def man2suoerman(man:Man):SuperMan = new SuperMan(man.name)
val man = new Man("若泽")
man.fly
}
}
class Man(val name:String){
def eat() : Unit = {
println("Man eat")
}
}
class SuperMan(val name : String){
def fly():Unit = {
println(s"$name fly")
}
}
implicit def file2RichFile(file:File) : RichFile = new RichFile(file)
如果觉得隐式转换都写在代码中很乱,可以把隐式转换单独写在一个文件中,然后在文件头import导入
package scala
import java.io.File
object ImplicitAspect {
implicit def man2suoerman(man:Man):SuperMan = new SuperMan(man.name)
implicit def file2RichFile(file:File) : RichFile = new RichFile(file)
}
在spark源码中有大量的隐式转换,最常见的就是rdd的转换,由基础的rdd转化为高级的RDD