Scala中 unapply方法和 apply 方法相反,
apply是传递一个参数生成一个类, Unapply方法是 根据传递的类 获取参数,逆向的过程
在spark编程中 可以使用unapply 方法进行,模糊匹配 和 进行提取
eg1:
class People(val name:String){
def peopleInfo(): Unit ={
println("this people‘s name is :")
}
}
object People{
def apply(name:String): People ={
return new People(name)
}
def unapply(c:People): Option[String] ={
return Some(c.name)
}
}
var People(getName) = People("张三") //这里等号右边 是调用的apply方法生成 实例化对象, 等号左边是调用了 unapply 方法,把等号右侧的实例化对象,提取出对象属性
println(getName)
输出:
PS:上例中的 返回值是 Option 一种抽象类 ,当不知道返回值类型是什么数据类型时候,就可以设置为 Option类
return 的是Some 是Option的一个子类,
详细介绍 https://blog.youkuaiyun.com/hzp666/article/details/116056680
eg2:
class Animal(val name:String, val theType:String){
def animalInfo(): Unit ={
printf("this Animal‘s name is %s, type is %s", name, theType)
}
}
object Animal{
def apply(name:String,theType:String): Animal ={
return new Animal(name,theType)
}
def unapply(c:Animal): Option[(String,String)] ={
return Some(c.name,c.theType)
}
}
val animal1 = Animal("大黄","狗狗") //调用apply方法 生成实例化对象
animal1.animalInfo()
println("")
val Animal(n,t) = animal1 //调用unapply方法 获取对象的属性
printf("the animal's name is %s, and the type is %s",n,t)
输出:
eg3: