scala——面向对象:2. 构造器

构造器:

主构造器:类名后面加参数列表

辅助构造器:在主构造器内,添加参数,使用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")

}

}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值