package com.example.extensiondemo
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val inputEditText = findViewById<EditText>(R.id.inputEditText)
val showLengthButton = findViewById<Button>(R.id.showLengthButton)
val lengthTextView = findViewById<TextView>(R.id.lengthTextView)
showLengthButton.setOnClickListener {
val inputText = inputEditText.text.toString()
lengthTextView.text = inputText.formattedLength()
}
}
}
fun String.formattedLength(): String {
return "Length: ${this.length}"
}We created an extension function formattedLength on the String class. This function returns a string showing the length of the string in a friendly format.
In the MainActivity, when the user taps the 'Show Length' button, we get the text from the EditText, call the extension function on it, and display the result in the TextView. This shows how extension functions let us add new behavior to existing classes without changing their code.