有没有办法覆盖默认对象打印

时间:2012-01-14 01:31:08

标签: scala println

我正在尝试在scala中打印一个类。定义如下:

class Player(balance : Int, player_num :Int ){
    var curHand = new ArrayBuffer[Int]()
    var sum = 0

    def method1()={
        ....
    }
}

我想用控制台打印到控制台:

var player1 = new Player(100,1)
println(player1)

有没有办法可以像在java中一样覆盖toString运算符以实现此目的,或者我必须创建一个类似的方法:

def print(){
    println("balance " + balance + "Player number" + player_num)
}

并致电

var player1 = new Player(100,1)
player1.print()

1 个答案:

答案 0 :(得分:9)

override def toString = "balance " + balance + " Player number " + player_num