String Data type Usage and Type Conversion in Kotlin


Kotlin String Overview and Definition

  • A string is a collection of characters. 
  • A String is immutable.
  • The type can be either declared explicitly or the compiler itself has the ability to infer the type of the assigned value. There are 2 types of String. They are
    • Escaped String
    • Raw String

Escaped String

  • An escaped String is represented by "Value". An escaped String can have escape characters like "\n", "\t", etc. 
  • An escaped String is much similar to the Java String.

Raw String

  • The raw string is represented by """Value""" and it can contain new lines.
  • When a new line is added, by default  "|" is added as the delimiter to refer a new line in the raw string. The method ".trimMargin()" removes the delimiter.
  • A delimiter of our own choice can also be provided by mentioning the required delimiter in the "trimMargin()" method like "trimMargin(>)"

Syntax and declaration

Thus a String can be declared by 3 ways as mentioned below.

1. Mentioning type explicitly

//Escaped String
val variable_name : String= " "
//Raw String
val variable_name : String= """ """

for example,

val name : String = "Little\nDrops"
val name : String = """Little
        |
        |
        |Drops""".trimMargin()

2. Number type is automatically inferred

//Escaped String
val variable_name = "value"
//Raw String
val variable_name = """ """

for example,
//Data type is automatically inferred
val name = "Little\nDrops"
val name = """Little
        |
        |
        |Drops""".trimMargin()

3. Declaring and Initializing separately

var variable_name : String
variable_name = "value"

for example,

//Declaring and Initializing separately
var name : String
name = "Little\nDrops"


var name : String
name = """Little
        |
        |
        |Drops""".trimMargin()

String Datatype Example Program in Kotlin

// String Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args:Array<String>) {
    //Assigning value to String variable explicitly
    val a : String  = "Little\nDrops"
    //Assigned value is inferred automatically by compiler
    val b = """Little
        |
        |
        |Drops""".trimMargin()

    println("Value of a is $a")
    println("Value of b is $b")
}

Sample Output

Value of a is Little
Drops
Value of b is Little


Drops