Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 693
tigga4392 Avatar asked Dec 14 '25 06:12

tigga4392


2 Answers

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
like image 174
elyasib Avatar answered Dec 15 '25 19:12

elyasib


You should override toString method of your TestClass.

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

like image 22
vvg Avatar answered Dec 15 '25 19:12

vvg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!