Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override toString method in Scala and replace it with a dynamic text

Tags:

java

scala

I'm trying to override the toString method in Scala. It has to return the time passed since an instance of the class is created. The time passed is computed in timePassed() method.

I have no idea on how to force the toString method to execute the timePassed method and generate an appropriate results when I call it.

like image 279
Mohsen Avatar asked Oct 29 '25 15:10

Mohsen


1 Answers

toString isn't magic, it's free to call whatever methods it wants, have local variables, etc.

override def toString = s"The LED has a status of ${timePassed()}."

or

override def toString = {
  val internalTime = timePassed()
  s"The LED has a status of $internalTime."
}
like image 115
Alexey Romanov Avatar answered Oct 31 '25 06:10

Alexey Romanov