Sobes.tech
Middle

How is an extension added and what exactly can be added?

sobes.tech AI

Answer from AI

Extensions are added to classes, properties, functions, or receiver types.

You can add:

  • New functions to an existing class.
  • New properties to an existing class.
  • New helper functions for a specific receiver type.

Example of adding an extension function:

fun String.toUpperCaseFirstChar(): String {  
    // Returns a string where the first character is in uppercase
    return this.substring(0, 1).toUpperCase() + this.substring(1)  
}

Example of usage:

val myString = "hello"
val capitalizedString = myString.toUpperCaseFirstChar()
// Now capitalizedString = "Hello"