Skip to content

Add option for generating toString() methods basing on fields #91

Description

@alexander-yevsyukov

Have a look at the Twitter thread which hinted me on this feature. The thread shows the way TypeScript defines new types basing on values of other types used in a string form.

Currently we have an ability in Java to add a mix-in interface which would allow to have a custom toString(), but it's too much work. A more simple approach would be to have a type option, which would be used by the CoreJvm Compiler for Java.

Obviously, we'll need to add the option to spine/options.proto under Base Libraries repo.

Template-based toString()

The option declaration could look something like this:

message Length {
   option (string_form).template = "${value}${units}";
   int value = 1 [(required) = true];
   LengthUnit units = 2 [(required) = true];
}

Delegated string form

Similarly to how we arrange calculated validation using MessageValidator SPI, we can have generated toString() delegating to a Stringifier of the corresponding message class. This behaviour would have a trigger in the message declaration via the delegated field:

message Length {
   option (string_form).delegated = true;
   int value = 1 [(required) = true];
   LengthUnit units = 2 [(required) = true];
}

The name delegated hides the implementation details. The generated code for languages other than Java may want to use other approaches that won't have the Stringifier concept.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    Status
    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions