scala 叠加在一起的特质 举例

1、编写Logged.scala:

trait Logged{
	def log(msg:String){}
}
class BankAccount(initialBalance:Double){
	//var balance=initialBalance
	private var balance=initialBalance
	def deposit(amount:Double)={balance+=amount;balance}
	def withdraw(amount:Double)={balance-=amount;balance}
	def query()=balance
}
class SavingsAccount(initialBalance:Double) extends BankAccount(initialBalance){
	private var num:Int=_
	def earnMonthlyInterest()={//每月执行一次
		num=3			//每月有三次免手续费(1元)
		super.deposit(1) //月利息1元
	}
	override def deposit(amount:Double)={
		if(num>0){num-=1;super.deposit(amount)}
		else super.deposit(amount-1)
	}
	override def withdraw(amount:Double)={
		if(num>0){num-=1;super.withdraw(amount)}
		else super.withdraw(amount+1)
	}
}
class SavingsAccount2(initialBalance:Double) extends SavingsAccount(initialBalance) with Logged{
	override def withdraw(amount:Double)={
		//if(amount>balance){log("Insufficient funds");-1} //withdraw返回一个Double型值,操作失败时,返回-1。
		//这里可以找到balance,是因为,基类里是没有private属性。但是这样做是不安全的。
		if(amount>query){log("Insufficient funds");-1} //withdraw返回一个Double型值,操作失败时,返回-1。
		else {log("withdraw success");super.withdraw(amount)}
	}
}
trait ConsoleLogger extends Logged{
	override def log(msg:String){println(msg)}
}
trait TimestampLogger extends Logged{
	override def log(msg:String){
		super.log(new java.util.Date()+" "+msg)
	}
}
trait ShortLogger extends Logged{
	val maxLength=15
	override def log(msg:String){
		super.log(
			if(msg.length<=maxLength) msg
			else msg.substring(0,maxLength-3)+"..."
		)
	}
}
2、编译:scalac Logged.scala

3、在scala的REPL里:

scala> val test=new SavingsAccount2(100) with ConsoleLogger with TimestampLogger

test: SavingsAccount2 with ConsoleLogger with TimestampLogger = $anon$1@1b75756

scala> test.withdraw(10)
Sun Jul 03 14:00:51 CST 2016 withdraw success
res18: Double = 89.0

scala> val test2=new SavingsAccount2(100) with ConsoleLogger with TimestampLogge
r with ShortLogger
test2: SavingsAccount2 with ConsoleLogger with TimestampLogger with ShortLogger
= $anon$1@9b0a6f

scala> test2.withdraw(10)
Sun Jul 03 14:01:59 CST 2016 withdraw suc...
res19: Double = 89.0

scala> val test3=new SavingsAccount2(100) with ConsoleLogger with ShortLogger wi
th TimestampLogger
test3: SavingsAccount2 with ConsoleLogger with ShortLogger with TimestampLogger
= $anon$1@81065e

scala> test3.withdraw(10)
Sun Jul 03 1...
res20: Double = 89.0



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值