This is the fourth part of the video series on Kotlin language. Read the first, second and third parts here. In this post, let’s discuss String.
String is an immutable type in Kotlin.
fun main(args:Array<String>){ var lang = "Java" println(lang) //Java lang = "Scala" println(lang) //Scala println(lang.javaClass) //java.lang.String }
You can access the characters of a String using the numerical index starting from 0 on the variable itself.
var lang = "Scala" println(lang[0]) println(lang[10]) //StringOutOfBoundsException lang[0] = "s" //ERROR because it's immutable
In the code above, lang[0] is used to access the first letter in the string. But, we cannot change the(or any) character as string is immutable.
Multi-line strings can be created using “””…”””, where whitespace characters are preserved.You can use the pipe(|) character as the starting letter of every line and trim the leading spaces using trimMargin() method.
var comments = """ |Kotlin |is |Cool """ println(comments.trimMargin())
The trimMargin() method takes a string argument that denotes the new delimiter. For example, in the code below, we have used tilde(~) as the delimiter instead of pipe(|).
var comments = """ ~Java ~is ~Cool ~too """ println(comments.trimMargin("~"))
You can find the video here.