构造器:
主构造器:类名后面加参数列表
辅助构造器:在主构造器内,添加参数,使用this定义
主构造器:
package test01
class StructDemo (val name: String, var age: Int, faceValue: Int){
//可以使用val、var修饰,没有val或var的无法访问
}
object StructDemo{
def main(args: Array[String]): Unit = {
val s = new StructDemo("ningning",18,98)
//s.name = "tom" val修饰的变量不能修改
s.age = 27
println(s.name)
println(s.age)
//println(s.faceValue) faceValue无法访问
}
}
辅助构造器:
package test01
class StructDemo (val name: String, var age: Int, faceValue: Int){
//可以使用val、var修饰,没有val或var的无法访问
var gender:String = _
//辅助构造器
def this(name:String, age:Int, faceValue:Int, gender:String){
this(name,age,faceValue) //辅助构造器第一行必须调用主构造器
this.gender = gender
}
}
object StructDemo{
def main(args: Array[String]): Unit = {
val s = new StructDemo("ningning",18,98,"male")
print(s.gender)
}
}
apply方法:助理方法,类似构造器,在伴生对象中做一些初始化操作
unapply方法:提取方法,提取固定数量的对象,
返回一个序列(Option类型),内部产生一个Some对象来存放一些值
参考:https://blog.csdn.net/bitcarmanlee/article/details/76736252
Option类型:在没有值的时候,使用None,这是Option的一个子类。
如果有值可以引用,就使用Some来包含这个值。Some也是Option的子类。
参考:https://www.jianshu.com/p/95896d06a94d
package test01
class ApplyDemo(val name:String, var age:Int, var faceValue:Int) {
}
object ApplyDemo{
def apply(name:String, age:Int, faceValue:Int): ApplyDemo =
new ApplyDemo(name,age,faceValue)
def unapply(applyDemo: ApplyDemo): Option[(String, Int, Int)] = {
if (applyDemo == null){
None
}else{
Some(applyDemo.name, applyDemo.age, applyDemo.faceValue)
}
}
}
object Test{
def main(args: Array[String]): Unit = {
val applyDemo = ApplyDemo("tom",24,98)
applyDemo match{
case ApplyDemo("tom", age, faceValue) => println("age:"+age)
case _ => println("No match nothing")
}
}
}