Calling Multiple Methods in Kotlin

Kotlin lets you call multiple methods on the same object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class StringParser(var string: String) {
    fun removeHTMLTags(): String {
        string = Regex("<[^>]*>").replace(string, "")
        return string
    }

    fun removeSpecialCharacters(): String {
        string = Regex("[^A-Za-z0-9 ]").replace(string, "")
        return string
    }

    fun removeLeadingAndTrailingSpaces(): String {
        return string.trim()
    }
}

fun main(args: Array<String>) {
    val htmlString = """
        <html>
            <header><title>This is a title</title></header>
            <body>
                Hello world!!!
            </body>
        </html>
    """.trimIndent()
    val stringParser = StringParser(htmlString)

    val response = with(stringParser) {
        removeHTMLTags()
        removeSpecialCharacters()
        removeLeadingAndTrailingSpaces()
    }

    println(response)
    // This is a title            Hello world
}

Using with you can chain all the method calls in the object instance and have it return the result of the last expression.

Updated: