Строки Groovy и GString
Освойте работу со строками в Groovy: одинарные, двойные и тройные кавычки, интерполяцию GString и многострочный текст для задач написания скриптов.
«Строки Groovy и GString» — бесплатный урок Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Groovy & Gradle: JVM Automation and Build Engineering, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Strings in Groovy
Groovy gives you several string literals, each for a job. Picking the right one keeps scripts clean and dodges escaping headaches.
Single-Quoted Strings
Single quotes make a plain String with no interpolation — what you type is exactly what you get.
def s = 'Hello World'
println sDouble-Quoted GStrings
Double quotes make a GString: any expression inside ${...} is evaluated and dropped into the text.
def name = "Alice"
println "Hello, ${name}!"Simplified Interpolation
For a single variable you can skip the braces and just put a dollar sign before the name.
def user = "Bob"
println "Welcome $user"Expressions Inside GStrings
Any expression fits inside ${...} — method calls, arithmetic, whatever you need.
def a = 3, b = 4
println "Sum is ${a + b}"Triple-Quoted Strings
Triple single quotes give a multiline plain string — ideal for text blocks without escaping every newline.
def text = '''Line one
Line two
Line three'''
println textTriple Double Quotes
Triple double quotes are multiline and support interpolation — perfect for templated output.
def title = "Report"
def doc = """=== ${title} ===
Generated by Groovy"""
println docSlashy Strings
Slashy strings (between forward slashes) skip backslash escaping — great for regexes and file paths.
def pattern = /\d{4}-\d{2}/
println patternLazy GString Evaluation
A GString can embed a closure (${-> ...}) that re-evaluates on each render, capturing live values instead of a snapshot.
def count = 1
def g = "Count: ${-> count}"
count = 2
println gUseful String Methods
Groovy adds handy string methods like padLeft and reverse, plus easy slicing with index ranges.
def s = "Groovy"
println s.reverse()
println s[0..2]GString vs String Equality
A GString isn't a String, but they compare equal and auto-convert. Call toString() when the exact type matters, like map keys.
def k = "id_${1}".toString()
def m = [(k): "value"]
println m["id_1"]Quick Check
Test your Groovy string knowledge.
Recap
You mastered Groovy strings: plain vs GString, triple-quoted multiline, slashy strings for regex, and lazy ${-> ...} closures.
Часто задаваемые вопросы
Урок «Строки Groovy и GString» бесплатный?
Да — полный текст урока «Строки Groovy и GString» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Groovy & Gradle: JVM Automation and Build Engineering, подпишись на CoddyKit PRO. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.
Чему я научусь в уроке «Строки Groovy и GString»?
Освойте работу со строками в Groovy: одинарные, двойные и тройные кавычки, интерполяцию GString и многострочный текст для задач написания скриптов. Ты практикуешь Groovy & Gradle: JVM Automation and Build Engineering с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Groovy & Gradle: JVM Automation and Build Engineering?
Предыдущий опыт не требуется. Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Строки Groovy и GString»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Groovy & Gradle: JVM Automation and Build Engineering?
Да. Каждый урок Groovy & Gradle: JVM Automation and Build Engineering включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в Groovy и JVM
- Синтаксис Groovy и базовые типы
- Скрипты Groovy и GShell
- Строки Groovy и GString