Kotlin – Initialize String
To initialize a String variable in Kotlin, we may assign the String literal to the variable without specifying explicit type, or we may declare a variable of type String and assign a String literal later.
The following is a sample code snippet to initialize a variable with a String literal.
var myString = "Hello World"
The following is a sample code snippet to first declare a variable of type String, and then initialize this variable with a String literal.
var myString: String
myString = "Hello World"
Examples
In the following program, we will initialize a variable with a String literal. Since we are initializing the variable with a value, the type of the variable is derived implicitly from the type of value assigned.
Main.kt
fun main(args: Array<String>) {
var myString = "Hello World!"
print(myString)
}
Output
Hello World!
Now, let us declare a variable of type String. And then in the next statement, we will initialize a String literal to it.
If we are not initializing the variable during the declaration itself, the type of the variable has to be specified.
Main.kt
fun main(args: Array<String>) {
var myString: String
myString = "Hello World"
print(myString)
}
Output
Hello World!
Conclusion
In this Kotlin Tutorial, we learned how to initialize a String variable in Kotlin.