packagecom.learn.scala.day15
/**
* scala第十五天
* Created by zhuqing on 2017/3/16.
*/
objectDay15Apply {
defmain(args: Array[String]): Unit = {
/**
* 创建Person类,实际调用的是: val person = Person.apply("001","Robbie");
*
*/
valperson =Person("001","Robbie");
/**
* 解开Person,实际调用的是: var idname = Person.unapply(person)
*/
valPerson(id,name) = person
println(id+":"+name)
validname:Option[(String,String)] = Person.unapply(person)
val(id1,name1) = idname.get
println(id1+":"+ name1)
/**
* 默认调用Person的update方法:
* def update(id:String ,name:String): Unit
*/
person("002") ="Tome";
println(person)
/**
* 实际调用的是:
* Name.unapplySeq("Robbie T Zhu")
*/
valName(fistName,middleName,secondName)="Robbie T Zhu"
println(fistName+" "+middleName+" "+secondName)
}
}
packagecom.learn.scala.day15
importscala.beans.BeanProperty
importscala.collection.mutable
/**
* Created by zhuqing on 2017/3/16.
*/
classPerson(@BeanPropertyvalid:String,@BeanPropertyvarname:String) {
def this(id:String) {
this(id,"None")
}
/**
* 更新数据,一般在集合和Map中常用,在这里使用不妥。
*@param id
*@param name
*/
defupdate(id:String,name:String): Unit ={
this.name = name;
}
override deftoString:String= {
"("+ id +","+ name +")"
}
}
/**
* Person 的伴生类
*/
objectPerson {
/**
* 创建Person
*
*@param id
*@param name
*@return
*/
defapply(id:String, name:String): Person =newPerson(id, name)
/**
* 创建person
*
*@param id
*@return
*/
defapply(id:String): Person =newPerson(id)
/**
* 把Person拆解成id和姓名的tupe
*@param arg
*@return
*/
defunapply(arg: Person): Option[(String,String)] = {
if(arg ==null) {
None
}else{
Some((arg.getId, arg.getName))
}
}
}
objectName{
/**
* 把输入的数据拆解成一个序列
*@param input
*@return
*/
defunapplySeq(input:String):Option[mutable.Seq[String]]={
if(input==null|| input.isEmpty){
None
}else{
Some(input.split(" "))
}
}
}