Object methods: @EqualsAndHashCode, @ToString, @CopyWith

@EqualsAndHashCode, @ToString and @CopyWith give a data class ==, hashCode, toString() and a copy with some values changed, written by the generator from the class's fields.

Why

A data class needs the same methods again and again: two objects with the same values should be equal and find each other in a Set, toString() should show the fields, and changing one value should not mean copying all the others by hand. Writing and maintaining them is error-prone (a new field is forgotten in hashCode), and a toString() easily prints a password into a log.

The three annotations ask the generator to write them. Each makes the class described (no @Introspected needed). Options are parameters only.

Example

import 'package:spring_core_dart/spring_core_dart.dart';
// copyWith is in the module's generated file:
import 'package:shop/spring_gen/src/app.spring.introspection.dart';

@EqualsAndHashCode()
@ToString(mask: ['card'])
@CopyWith()
class Book with IntrospectedObject {
  const Book({
    required this.title,
    this.pages = 0,
    this.tags = const [],
    this.card,
  });

  final String title;
  final int pages;
  final List<String> tags;
  final String? card;
}

final dune = Book(title: 'Dune', tags: ['sf', 'classic']);

dune == Book(title: 'Dune', tags: ['sf', 'classic']); // true (lists by content)
dune.toString();
// Book(title: Dune, pages: 0, tags: [sf, classic], card: ******)
dune.copyWith(pages: 412);        // the other values are kept
dune.copyWith(card: null);        // null clears a nullable field

What is generated, and where

Nothing is written into your file. The generator puts the code into the module's lib/spring_gen/<library>.spring.introspection.dart:

The mixin IntrospectedObject (the framework's, written once by hand) finds the functions by the object's runtime type: its ==, hashCode and toString() call them. So the class says with IntrospectedObject, and the build tells you when it is missing. A subclass without a description of its own uses its closest described superclass's.

copyWith is not a member of the class, so the library that calls it imports the generated file. The class's own file needs nothing.

The annotations

Annotation Parameters What it gives
@EqualsAndHashCode include, exclude, callSuper == and hashCode
@ToString include, exclude, includeNames, callSuper, mask, reveal toString(): Book(title: Dune, pages: 412)
@CopyWith include, exclude, constructor a typed copyWith

Fields

The fields are the public instance fields the class declares, in their order. include names exactly those to use, exclude those to leave out (not both), and callSuper adds the superclass's part (its own description's, or its own methods). Fields typed List, Set and Map compare and hash by content, nested ones too. Objects of different classes are never equal. A private field cannot be read from the generated library: it is left out, with a warning.

Without a description registered, the three methods throw a StateError that says how to register it. They never compare by identity silently.

Masking secrets

@ToString writes a field whose name looks secret (password, apiKey, refresh_token, ...) as ******, and so does a field named in mask. reveal shows a field the rule would hide. It is decided at build time: the value of a masked field is never read.

In logs, objects are printed through toString(), so the masking applies there. It does not apply to JSON output: keep a field out of JSON with @JsonProperty('', access: JsonPropertyAccess.writeOnly).

copyWith

An argument left out keeps the value, null clears a nullable field, and a value of the wrong type does not compile. The copy is made by the unnamed constructor (or the one constructor names), so each field must match a constructor parameter.

In a unit test

The context registers the descriptions as it starts. A unit test without a context registers them itself, with the getter of the generated file:

import 'package:shop/spring_gen/src/app.spring.introspection.dart';

void main() {
  setUpAll(() => Introspector.shared.registerAll($appIntrospections));
  // ...
}

Build errors

The build fails for every misuse, each with a message that names the fix: the annotations on a mixin, enum or abstract class, a class without with IntrospectedObject, include together with exclude, a name that is no field (with a "did you mean"), a name in mask and exclude, and a constructor that copyWith cannot use. It warns about a field in hashCode that is not final.

There is no build key: the methods are the application's behaviour at run time, in every build.

In Spring (Java)

Spring has no such annotations. Lombok has them, and they are what these follow:

@EqualsAndHashCode(exclude = "cover")
@ToString(exclude = "cover")
@With
class Book { String title; int pages; byte[] cover; }

Spring's own helpers are the hand-written ways: ObjectUtils.nullSafeEquals, ObjectUtils.nullSafeHashCode and ToStringCreator.

Differences that matter:

See also