Updated 28 February 2019
Extensions function in kotlin provide the ability to extend the class with new functionality without extends the class. Extensions function do not modify class they extend the class and insert new functionality in the class.
Let’s begin with very basic we know that to show a simple Toast in an Activity we have to write boilerplate code we have to pass context, message and the duration in makeText() method. Then the question arises how extension function can make our life easy so let’s start with Toast now I going to show you how we can extend the Activity class and add new functionality to just show toast anywhere in activity all we have to do just call showToast() method and pass the message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// In Activity Class without Extension function class BaseActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { super.onCreate(savedInstanceState, persistentState) Toast.makeText(getApplicationContext(), "Hello Extension Function",Toast.LENGTH_LONG).show(); } } // In Activity Class with Extension function class BaseActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { super.onCreate(savedInstanceState, persistentState) showToast("Hello Extension Function") } } fun Activity.showToast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show() } |
In the above example, we have seen how extension function we can write to just show a Toast and call it in any activity in our application.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.