Skip to end of metadata
Go to start of metadata

Strings are represented by the type String. Strings are immutable. Elements of a string are characters can be accessed by the indexing operation: s[i]. A string can be iterated over with a for loop:

for (c in str) { 
  println(c) 
}

String literals

Kotlin has two types of string literals: escaped strings that may have escaped characters in them and raw strings that can contain newlines and arbitrary text. An escaped string is very much like a Java string:

val s = "Hello, world!\n"

Escaping is done in the conventional way, with a backslash.

A raw string is delimited by a triple quote ("""), contains no escaping and can contain newlines and any other characters:

val text = """ 
  for (c in "foo") 
    print(c) 
"""

Templates

Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the string. A template expression starts with a dollar sign ($) and consists of either a simple name:

val i = 10 
val s = "i = $i" // evaluates to "i = 10"

or an arbitrary expression in curly braces:

val s = "abc" 
val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"

What's next

Labels:
None
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Jul 20, 2011

    Anonymous

    While I quite like String templates (I use them a lot in my Groovy development), there is the possibility of string template injection attacks to worry about. Have you considered any language features to minimize the security risk of using string templates?

    1. Jul 21, 2011

      String templates are converted into bytecode at compile time, so there's no security risk: the template text cannot be provided by an attacker.

    2. Jul 21, 2011

      Anonymous

      I would expect that string templates are just compile-time syntactic sugar in Kotlin (i.e. they only work in string literals, not in arbitrary strings).

  2. Jul 21, 2011

    Anonymous

    1. What kinds of expressions are allowed in $

    Unknown macro: {...}

    ?

    2. Is it possible to use String templates with lazy evaluation, so that it would finally be possible to code an intelligent logging library that doesn't evaluate the String if logging is disabled? Example:

    I would want to get rid of workarounds such as log.isDebugEnabled().

    1. Jul 21, 2011

      1. Well, any expression

      2. debug() function will take function, that evaluates debug expression instead of expression itself and call it lazily. All in all it'll look like

      1. Jul 21, 2011

        Anonymous

        Cool, thanks. I should get used to functional programming style.

    2. Jul 21, 2011

      Anonymous

      Uups, should read:

      1. What kinds of expressions are allowed in ${...} ?

  3. Jul 21, 2011

    So a literal dollar sign takes a backslash to escape & prevent template evaluation?

    1. Jul 21, 2011

      True

  4. Jul 22, 2011

    Anonymous

    Can raw string contain a template expression?

    Single line templates seem to me quite useless.

    1. Jul 22, 2011

      Yeah, that indeed would be great but that would mean those strings aren't raw anymore, since dollar sign needs to be escaped. We'll probably need both multiline strings and raw strings. Ideas for particular syntax are welcome!

      1. Jul 22, 2011

        Anonymous

        Perl provides a lot of possibilities here ... consider their "here" strings (taken from sh, but more powerful/general).

  5. Jul 22, 2011

    Anonymous

    How big is a char? If it's 16 bits, and strings are indexable, then you've completely screwed it up. Even Java now has a full-unicode API, as inconvenient and error-prone as it is. The only language I've seen that has come close to doing chars and strings right is D, which provides chars and strings in all three code unit sizes.

    1. Jul 23, 2011

      Currently we just reuse Java platform's data format for chars and strings. The Unicode-aware API will be present, of course, but the performance penalty of this API is not going away, so we'll keep the default naive indexing around.

  6. Dec 25, 2012

    Is there a nice way to format interpolated numbers?

    Let's say I want to show "probability is ${p * 100}" with just two decimal points. I came up with this:

    public inline fun Number.toString(formatStr: String): String = java.lang.String.format(formatStr, this) 
     
    println("probability is ${(p * 100).toString("%4.2f")}")

    Is there a better way? Or should we add this overloaded toString into the standard library?

    I'm trying to imagine a better syntax for this...

    println("hello ${p*100, "%4.2f"}")
    - semantically this might mean that operation ${V} is translated to V.toString() and ${V, A, B, ...} is V.toString(A, B, ...)

    1. Dec 25, 2012

      I think adding Double.format() to standard library is a good idea (toString() is an odious name)