tigga4392
tigga4392

Reputation: 111

Scala how to print contents of a class's returned string and not Class@3c8bdd5b

Is there an easy way to print the contents of what is returned from a new class object? I am testing with Fun Suite. Please see example below:

test("test") {
val contentString = new TestClass("test")
println("CONTENT IS: " + contentString)
}

The output is "CONTENT IS: TestClass@3c8bdd5b" and I would like to see "CONTENT IS: actual string content"

Thanks

Upvotes: 3

Views: 3685

Answers (2)

elyasib
elyasib

Reputation: 21

You need to override the toString method. If you defined the class, you can do it inside the class definition as usual, e.g.:

 class TestClass(val x: String){
   override def toString = x
 }

otherwise, you can extend the TestClass or create an anonymous class overriding the toString method, e.g.:

 class TestClass(val x: String){
 }

 val z = new TestClass("hello world"){
     override def toString = x
   }   // this will show " z: TestClass = hello world " in the REPL

Upvotes: 2

vvg
vvg

Reputation: 6385

You should override toString method of your TestClass.

Another possible solution use "case classes" that provides toString implementation.

Upvotes: 1

Related Questions