| Start |
|---|
| Potential Pitfall: Extensions are Resolved Statically The extension method to be called is determined at compile-time based on the reference-type of the variable being accessed. It doesn't matter what the variable's type is at runtime, the same extension method will always be called. The above example will print |
| Top-Level Extensions Top-level extension methods are not contained within a class. Above an extension method is defined for the type This extension can be called like so: |
| Lazy extension property workaround Assume you want to create an extension property that is expensive to compute. Thus you would like to cache the computation, by using the lazy property delegate (opens new window) and refer to current instance ( In the example, the extension property is |
| Sample extending Java 7+ Path class A common use case for extension methods is to improve an existing API. Here are examples of adding Which can now be invoked in this example: |
| Sample extending long to render a human readable string Given any value of type Then easily used as: |
| Sample extending Java 8 Temporal classes to render an ISO formatted string With this declaration: You can now simply: |
| Using extension functions to improve readability In Kotlin you could write code like: But the use of You could now write the code as: Which now let's people know what to expect within the lambda parameter. Note that the type parameter |
| Extension functions to Companion Objects (appearance of Static functions) If you want to extend a class as-if you are a static function, for example for class |
| Extensions for easier reference View from code You can use extensions for reference View, no more boilerplate after you created the views. Original Idea is by Anko Library (opens new window) ExtensionsUsageSyntax
RemarksExtensions are resolved statically. This means that the extension method to be used is determined by the reference-type of the variable you are accessing; it doesn't matter what the variable's type is at runtime, the same extension method will always be called. This is because declaring an extension method doesn't actually add a member to the receiver type. |
Read Article
https://develop.horje.com/learn/1434/reference