279
CHAPTER 10: Development
Multiline
String Literals
Multiline string literals in Java always were a little clumsy to define.
String s = "First line\n" +
"Second line";
In Kotlin you can define multiline string literals as follows:
val s = """
First line
Second Line"""
You can even get rid of the preceding indent spaces by adding
.trimIndent()
as follows:
val s = """
First line
Second Line""".trimIndent()
This removes the leading newline and the common spaces at the beginning of each line.
Inner
Functions and Classes
In Kotlin, functions and classes can also be declared inside other functions, which further
helps in structuring your code.
fun someFun() {
...
class InnerClass { ... }
fun innerFun() = ...
...
}
The scope of such inner constructs is of course limited to the
function in which they are
declared.
String Interpolation
In Kotlin you can pass values into strings as follows:
val i = 7
val s = "And the value of 'i' is ${i}"
This is borrowed
from the Groovy language, and you can use it for all types since all types
have a
toString()
member. The only requirement
is that the contents of
${}
evaluate to an
expression, so you can even write the following:
val i1 = 7
val i2 = 8
val s = "The sum is: ${i1+i2}"
280
CHAPTER 10: Development
or write more complex constructs using method calls and lambda functions:
val s = "8 + 1 is: ${ { i: Int -> i + 1 }(8) }"
Qualified “this”
If
this
is not what you want but you
instead want to refer to
this
from an outer context, in
Kotlin you use the
@
qualifier as follows:
class A {
val b = 7
init {
val p = arrayOf(8,9).apply {
this[0] += this@A.b
}
...
}
}
Delegation
Kotlin allows for easily following the delegation pattern. Here’s an example:
interface Printer {
fun print()
}
class PrinterImpl(val x: Int) : Printer {
override fun print() { print(x) }
}
class Derived(b: Printer) :
Printer by b
Here, the class
Derived
is
of type
Printer
and delegates all its method calls to the
b
object.
So, you can write the following:
val pi = PrinterImpl(7)
Derived(pi).print()
You are free to
overwrite method calls at will, so you can adapt the delegate to use new
functionalities.
class Derived(val b: Printer) : Printer by b {
override fun print() {
print("Printing:")
b.print()
}
}