Kotlin multiline-string annotation parameters

859 views Asked by At

In Java, now that it supports text blocks, you can do this:

@Schema(description = """
            Line one.
            Line two.
            """)
public void someMethodName() { ... }

In Java, text blocks are compile-time constants and they automatically remove the indents. But in Kotlin, if you do this:

@Schema(description = """
            Line one.
            Line two.
            """)
fun someMethodName() { ... }

you end up with unwanted spaces in front of each line. Unfortunately, you can't use trimMargin() or trimIndent() because they are not compile-time constants. Is there a way to make it look as nice in Kotlin as it does in Java?

1

There are 1 answers

1
flamewave000 On BEST ANSWER

Unfortunately for your use case, I don't think so. The point of the triple quote is to provide a way to write "Formatted" text into a string. If Java doesn't behave the same way as Kotlin, then technically it's the odd one out as any other language I've used behaves the same way as Kotlin. Your best alternative would be something like the following:

@Schema(description = "Line one.\n"
                    + "Line two.\n"
                    + "Line three.")
fun someMethodName() { ... }

The string concatenation will be performed at compile time since it is between literals.