Strings: Interpolation
● Beginner2 min
Write any expression in braces inside a string, and its value is put in its place.
fn main() {
const name = "asha"
const age = 31
print("{name} turns {age} this year")
}The program ran and printed:
kavach run insert.kav
asha turns 31 this yearThe braces can hold a calculation too. To write a brace itself, put a backslash before it:
fn main() {
const items = 3
const price = 40
print("{items} items cost {items * price}")
print("a literal brace: \{items}")
}The program ran and printed:
kavach run interp.kav
3 items cost 120a literal brace: {items}
In text on one line, a { must close on that line. One left open is an error at the brace, with the fix:
fn main() {
const open = "{"
print("a brace: {open}")
}The compiler refused the program:
kavach run brace-open.kav
error: this `{` is never closed: write `\{` for a brace in text (spec 1.7)A {…} that holds only text gives a warning, because it is almost always a brace that needed \{. Here the second line is one string, with the text or t == inside its braces, not two comparisons:
fn is_brace(t: String) -> Bool {
t == "{" or t == "}"
}
fn main() {
print(is_brace("\{"))
print(is_brace(" or t == "))
}The compiler warned, then the program ran:
kavach run brace-text.kav
warning: this `{…}` holds only text, so the string goes on past it: write `\{` for a brace, or the text itself (spec 1.7)falsetrue