středa 9. května 2018

Kotlin - Append to StringBuilder using "+" "plus" instead of append() method

Kotlin - Override plus operator for StringBuilder

Kotlin - Append to StringBuilder using “+” “plus” instead of append() method

In Kotlin you can easily override operator. I will show simple example how can this help you to write more readable code.

At first we will override “plus” operator on for StringBuilder class

operator fun StringBuilder.plus(str: String): StringBuilder {
    append(str)
    return this
}

If you define this function as private. It will be accessible only in file, where it is defined. Or public and then it can be used anywhere in project.

And from this code:

sb.append("function ").append(generatedClassName).append("() {").append("\n")
functions.forEach { function: Function ->
    sb.append(indent).append("this.").append(function.name).append(" = undefined;").append("\n")
}
sb.append("}").append("\n")
sb.append("var ").append(name).append(" = new ").append(generatedClassName).append("();").append("\n")

we can remove all ‘append’ words and we get this code:
=>

sb + "function " + generatedClassName + "() {" + "\n"
functions.forEach { function: Function ->
    sb + indent + "this." + function.name + " = undefined;" + "\n"
}
sb + "}" + "\n"
sb + "var " + name + " = new " + generatedClassName + "();" + "\n"

Very simple, code is shorter and more readable.

Žádné komentáře:

Okomentovat