toString

steps.annotation.toString
final class toString extends MacroAnnotation

A macro annotation that automatically generates a custom toString method for a class.

The @toString annotation can be applied to a class, object, or trait. When applied, it overrides the toString method to include the class name and the values of all fields marked as ParamAccessor.

If the class already defines or overrides the toString method, the annotation will emit a warning indicating that the annotation is not necessary. The existing toString method will remain unchanged.

Example usage:

@toString
class MyClass(val a: Int, val b: String)

val instance = MyClass(1, "hello")
println(instance.toString) // Output: MyClass(1, hello)

The generated toString method produces output in the format: ClassName(field1, field2, ...).

Attributes

Note

This annotation requires Scala's experimental flag to be enabled, or it can be used within a scope marked as experimental (i.e., using import scala.annotation.experimental). This is necessary because it relies on experimental macro annotation features.

Experimental
true
Graph
Supertypes
trait MacroAnnotation
trait StaticAnnotation
class Annotation
class Object
trait Matchable
class Any
Show all

Members list

Value members

Concrete methods

override def transform(using Quotes)(tree: x$1.reflect.Definition): List[x$1.reflect.Definition]

Transforms the annotated class to add a custom toString method.

Transforms the annotated class to add a custom toString method.

If the class already overrides toString, a warning is emitted and no changes are made. Otherwise, this annotation adds a new toString method that returns a string representation of the class name and its fields.

Value parameters

tree

The abstract syntax tree (AST) of the annotated class, object, or trait.

Attributes

Returns

The transformed class definition, with the generated toString method if applicable.

Definition Classes
MacroAnnotation