Extension Function in Kotlin

Level 3100 keystrokes

Adds a new method to the String class with an extension function.

Kotlin code

// String. before the name makes this an extension function of String
// The String class itself is not modified
1fun String.addExclaim(): String {
// this is the String the function was called on; append "!" to it
2 return this + "!"
3}
4
// A normal String value
5val text = "Hello"
// Call the extension like a regular method: prints Hello!
6println(text.addExclaim())

Output

Hello!
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • "× 4
  • (× 3
  • )× 3
  • .× 2
  • :× 1
  • !× 1
  • {× 1
  • }× 1
  • +× 1
  • =× 1

More Kotlin examples at level 3

← Kotlin typing practice