String Data type Usage and Type Conversion in Kotlin
On this page (10sections)
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 Frequently Asked Questions
What is String Data type Usage and Type Conversion in Kotlin?
String Data type Usage and Type Conversion is demonstrated in this Kotlin tutorial with a complete, runnable example and its sample output.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice String Data type Usage and Type Conversion?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.