scala简单的功能实现~weektwo
1、编写⼀个BankAccount类,假如deposit和withdraw⽅法,和⼀个只读的balance属性。
//存款(deposit)和取款()函数 class BankAccount extends App{ private var account:Int=0 def deposit(money : Int){ account += money println(s"the whole money is $account") } def withdraw(money : Int){ //assert(conditon)将在条件不成立的时候,抛出assertionError //assert(conditon,explanation)讲在条件不成立的时候,抛出explanation作为说明 assert(money<=account,"The money you withdraw should be less than account") account -=money println(s"the whole money is $account") } def balance=account }
2、编写Person类,主构造器接受⼀个字符串,字符串形式为名字,空格,姓,如 new Person(“Fred Smith”)。提供只读属性firstName和lastName。
class Person { val name="Fred Smith" val _name=name.split("\\s+") val firstName=_name(0) val lastName=_name(1) override def toString=s"the first name is $firstName,the last name is $lastName" }
3、定义⼀个Point类,使得我们不⽤new就可以直接使⽤Point(3,4)来构建类的实例。
class Point(val x:Int=0,val y:Int=0) { override def toString=("Point x is "+x+",Point y is "+y) } object Point{ def apply(x:Int=0,y:Int=0)=new Point(x,y) }
4、通过把scala.math.Ordered[Point]混⼊java.awt.Point⽅式,定义OrderedPoint类。按词典⽅式进 ⾏排序,也就是说,如果x1 < x2 或者 x1 = x2 且 y1 < y2, 则(x1,y1) < (x2, y2)