Implementing a toString() method in the superclass

Hello,

I want to implement the toString() method in the superclass to save time and space. Is there a way to do this? I want to print all fields of the respective class which are different for each subclass.

import org.example.Token

abstract class Expression{
abstract fun <T> visit(visitor:Visitor<T>):T

 //TODO: it should print all fields of a class
override fun toString():String {
 //TODO: implement
 return ""
}
class BinaryExpression(left:Expression,operator:Token,right:Expression):Expression(){
override fun <T> visit(visitor:Visitor<T>):T { return visitor.visit(this) }
 } 
 
class GroupingExpression(expression:Expression):Expression(){
override fun <T> visit(visitor:Visitor<T>):T { return visitor.visit(this) }
 } 
 
class LiteralExpression(value:Any):Expression(){
override fun <T> visit(visitor:Visitor<T>):T { return visitor.visit(this) }
 } 
 
class UnaryExpression(operator: Token, right:Expression):Expression(){
override fun <T> visit(visitor:Visitor<T>):T { return visitor.visit(this) }
}
 class PassExpression(operator:Token):Expression(){
  override fun <T> visit(visitor: Visitor<T>): T {
   println("this is a pass node - it represents an empty node.")
   return visitor.visit(this)
  }
 }
 

}

There is no easy way to do this. You can use reflection, but it sounds a little like an overkill. If you do this for debugging purposes only, it still could be a viable solution though.

The easiest would be to make your classes a data class or generate the code for them.

2 Likes

thanks!

Also, even a hard-coded method can be pretty concise, e.g.:

override fun toString() = "SubClass(prop1=$prop1, prop2=$prop2)"

Implementing one of those in each subclass shouldn’t be too onerous. (And it gives you the opportunity to customise it in each case, if you want.)