Skip to content

Instantly share code, notes, and snippets.

@nipafx
Last active February 21, 2024 16:58
Show Gist options
  • Save nipafx/e150b9e9d00bb8c4f6484dc3625e4ded to your computer and use it in GitHub Desktop.
Save nipafx/e150b9e9d00bb8c4f6484dc3625e4ded to your computer and use it in GitHub Desktop.
Creating multiline strings in JS, Groovy, Kotlin, and Java

#1 Split "one", "two" across two lines

Goal:

one\n
two

Onboard JavaScript requires us to break the code formatting.

		var lines = `one
two`

Groovy gives us another option: add a leading slash and newline, then call stripIndent().

		def lines1 = """one
two"""
		def lines2 = """\
			one
			two""".stripIndent()

Kotlin is similar, but the second option requires no slash because trimIdent() considers the leading newline as indentation. 🤔

		val lines1 = """one
two"""
		val lines2 = """
			one
			two""".trimIndent()

Java requires a leading newline:

		var lines = """
			one
			two""";

#2 Add a trailing newline

Goal:

one\n
two\n

JavaScript: Add the newline (code formatting interruption gets worse!).

		var lines = `one
two
`

Groovy: Add the newline (in option 1, code formatting interruption gets worse!).

		def lines1 = """one
two
"""
		def lines2 = """\
			one
			two
			""".stripIndent()

Kotlin: Add the newline (in option 1, code formatting interruption gets worse!).

		val lines1 = """one
two
"""
		val lines2 = """
			one
			two
			""".trimIndent()

Java: Add the newline.

		var lines = """
			one
			two
			""";

#3 Indent each line

Goal:

	one
	two

JavaScript: Add whitespace to line with opening delimiter (bonkers) and second line.

		var lines = `	one
	two
`

Groovy:

  1. Add whitespace to line with opening delimiter (bonkers) and second line, or
  2. Add Asciiart and switch from stripIndent to stripMargin.
		def lines1 = """	one
	two
"""
		def lines2 = """\
			|	one
			|	two
			""".stripMargin()

Again, Kotlin is very similar to Groovy with the bonkers option 1 and the Asciiart plus method switch in the other case:

		val lines1 = """	one
	two
"""
		val lines2 = """
		|	one
		|	two
		""".trimMargin()

Java: Indent each line.

		var lines = """
				one
				two
			""";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment