Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
199 views

Kotlin Extension Function - Javatpoint

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
199 views

Kotlin Extension Function - Javatpoint

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Home Kotlin Java Android PHP HTML CSS JavaScript jQuery Quiz Projects Interview Q Comment Forum Training

Kotlin Tutorial
Kotlin Tutorial
Environment Setup
Hello World Program
First Program Concept
Environment Setup (IDE)
First Program (IDE) Kotlin Extension Function ← Prev Next →

Kotlin Variable
Kotlin Data Type Kotlin extension function provides a facility to "add" methods to class without inheriting a class or
Kotlin Type Conversion using any type of design pattern. The created extension functions are used as a regular function inside
Kotlin Operator that class.
Kotlin Input/Output
Kotlin Comment The extension function is declared with a prefix receiver type with method name.
Control Flow Triggers in SQL (Hindi)

Kotlin if Expression fun <class_name>.<method_name>()  


Kotlin when Expression
Kotlin for Loop
In the above declaration, <class_name> is a receiver type and the <method_name>() is an extension
Kotlin while Loop
function.
Kotlin Do while Loop

⇧Return
SCROLLand TO
Jump
TOP
Continue Structure
Example of extension function declaration and its use
Function
In general, we call all methods from outside the class which are already defined inside the class.In below
Kotlin Function
example, a Student class declares a method is Passed() which is called from main() function by creating
Recursion Function
Default and Named Argument the object student of Student class.
Kotlin Lambdas
Higher order Function
Kotlin Inline Function

Array
Kotlin Array

String
Kotlin String

Exception Handling
Exception Handling
Kotlin Try Catch
Multiple Catch Block
Nested Try Block
Kotlin Finally Block
Kotlin Throw Keyword Suppose that we want to call a method (say isExcellent()) of Student class which is not defined in class. In
Null Safety such situation, we create a function (isExcellent()) outside the Student class as Student.isExcellent() and
Nullable Non Nullable Types call it from the main() function. The declare Student.isExcellent() function is known as extension
Kotlin Smart Cast function, where Student class is known as receiver type.
Unsafe and Safe Cast
Kotlin Elvis Operator
class Student{  
Collections
    fun isPassed(mark: Int): Boolean{  
Mutable Array
Kotlin Collections         return mark>40  
List: listOf()     }  
mutableListOf()
}  
Kotlin ArrayList
fun Student.isExcellent(mark: Int): Boolean{  
arrayListOf()
Map: mapOf()     return mark > 90  
Kotlin HashMap }  
hashMapOf()
fun main(args: Array<String>){  
mutableMapOf()
val student = Student()  
Set: setOf()
mutableSetOf() val passingStatus = student.isPassed(55)  
hashSetOf() println("student passing status is $passingStatus")  
Annotations   
Kotlin Annotations
val excellentStatus = student.isExcellent(95)  
Reflection println("student excellent status is $excellentStatus")  
Kotlin Reflection
}  
Kotlin OOPs
Class and Object
Output:
Nested and Inner Class
Kotlin Constructor
Visibility Modifier student passing status is true
Kotlin Inheritance student excellent status is true
Abstract Class
Kotlin Interface
Data Class The above example only demonstrates about how to declare an extension function.
Sealed Class
Extension Function Kotlin extension function example
Kotlin Generics
Let's see the real example of extension function. In this example, we are swapping the elements of
Ranges
Integer type range
MutableList<> using swap() method. However, MutableList<>class does not provide the swap() method
Kotlin Working Ranges internally which swap the elements of it. For doing this we create an extension function for
Kotlin Utility Function MutableList<> with swap() function.
Java Interoperability
The list object call the extension function (MutableList<Int>.swap(index1: Int, index2:
Calling Java code from Kotlin
Calling Kotlin code from Java Int):MutableList<Int>) using list.swap(0,2) function call. The swap(0,2) function pass the index value of list

Regex
inside MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int>) sxtension function.

Regular Expressions Introduction


Regex patterns fun MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int> {  
Android Startup val tmp = this[index1] // 'this' represents to the list  
Install Android Studio     this[index1] = this[index2]  
Hello World App
    this[index2] = tmp  
Kotlin Android
    return this  
Android TextView and EditText
}  
Kotlin Android Toast
Android Button fun main(args: Array<String>) {  
Android Custom Toast val list = mutableListOf(5,10,15)  
Android Explicit Intent
println("before swapping the list :$list")  
Android Implicit Intent
val result = list.swap(0, 2)  
Android ListView
Android AlertDialog println("after swapping the list :$result")  
Android Context Menu }  
Android Custom ListView
Android Options Menu
Output:
Android Popup Menu
Android WebView
Kotlin Android SeekBar before swapping the list :[5, 10, 15]
TabLayout with FrameLayout after swapping the list :[15, 10, 5]
TabLayout with ViewPager
DOM Parser
SAX Parser Extension Function as Nullable Receiver
XMLPullParser
JSON Parsing using URL The extension function can be defined as nullable receiver type. This nullable extension function is called
Android Media Player
through object variable even the object value is null. The nullability of object is checked using this ==
Android Video Player
null inside the body.
External Storage
Internal Storage
Let's rewrite the above program using extension function as nullable receiver.
SharedPreferences
SQLite Tutorial
Android Notification
Google reCAPTCHA
Authentication - Google Login
Google AdMob Banner Ads
Google AdMob Interstitial Ads funMutableList<Int>?.swap(index1: Int, index2: Int): Any {  
Google Map Current Location
if (this == null) return "null"  
Google Map Fixed Location
Google Map Search Location else  {  
Android Web Service val tmp = this[index1] // 'this' represents to the list  
this[index1] = this[index2]  
this[index2] = tmp  
return this  
    }  
}  
fun main(args: Array<String>) {  
val list = mutableListOf(5,10,15)  
println("before swapping the list :$list")  
val result = list.swap(0, 2)  
println("after swapping the list :$result")  
}  

Output:

before swapping the list :[5, 10, 15]


after swapping the list :[15, 10, 5]

Companion Object Extensions


A companion object is an object which is declared inside a class and marked with the companion
keyword. Companion object is used to call the member function of class directly using the class name
(like static in java).

A class which contains companion object can also be defined as extension function and property for the
companion object.

Example of companion object

In this example, we call a create() function declared inside companion object using class name (MyClass)
as qualifier.

class MyClass {  
    companion object {  
        fun create():String{  
            return "calls create method of companion object"  
        }  
    }  
}  
fun main(args: Array<String>){  
val instance = MyClass.create()  
}  

Output:
Sponsored

Looking for dealmaking and networking Sign Up


opportunities for your tech startup?
SLINGSHOT 2021
Recommended by

calls create method of companion object

Companion object extensions example

Let's see an example of companion object extensions. The companion object extension is also being
called using the class name as the qualifier.

class MyClass {  
    companion object {  
        fun create(): String {  
            return "calling create method of companion object"  
        }  
    }  
}  
fun MyClass.Companion.helloWorld() {  
println("executing extension of companion object")  
}  
fun main(args: Array<String>) {  
MyClass.helloWorld() //extension function declared upon the companion object  
}  

Output:

executing extension of companion object

Next Topic Kotlin Generics

← Prev Next →

For Videos Join Our Youtube Channel: Join Now

Feedback

Send your Feedback to feedback@javatpoint.com

Help Others, Please Share

Learn Latest Tutorials

Digital Marketing Elasticsearch Entity Framework Firewall

Functional Google Colab Graph Theory Groovy tutorial


Programming tutorial tutorial
Groovy
tutorial
Google Colab Graph Theory
Functional
Programming

Group Informatica Ionic tutorial ITIL tutorial


Discussion tutorial
Ionic ITIL
tutorial
Informatica
Group Discussion

IOS angular deep learning


Development material tutorial tutorial
tutorial
Angular Material Deep Learning
IOS with Swift

Preparation

Aptitude Logical Verbal Ability Interview


Reasoning Questions
Aptitude Verbal Ability
Reasoning Interview Questions

Company
Interview
Questions
Company Questions

Trending Technologies

Artificial AWS Tutorial Selenium Cloud


Intelligence tutorial Computing
AWS
Tutorial tutorial
Selenium
Artificial Cloud Computing
Intelligence

Hadoop tutorial ReactJS Data Science Angular 7


Tutorial Tutorial Tutorial
Hadoop
ReactJS Data Science Angular 7

Blockchain Git Tutorial Machine DevOps


Tutorial Learning Tutorial Tutorial
Git
Blockchain Machine Learning DevOps

B.Tech / MCA

DBMS tutorial Data Structures DAA tutorial Operating


tutorial System tutorial
DBMS DAA
Data Structures Operating System

Computer Compiler Computer Discrete


Network tutorial Design tutorial Organization and Mathematics
Architecture Tutorial
Computer Network Compiler Design
Computer Discrete
Organization Mathematics

Ethical Hacking Computer Software html tutorial


Tutorial Graphics Tutorial Engineering
Web Technology
Tutorial
Ethical Hacking Computer Graphics
Software
Engineering

Cyber Security Automata C Language C++ tutorial


tutorial Tutorial tutorial
C++
Cyber Security Automata C Programming

Java tutorial .Net Python tutorial List of


Framework Programs
Java Python
tutorial
Programs
.Net

Control Data Mining Data


Systems tutorial Tutorial Warehouse
Tutorial
Control System Data Mining
Data Warehouse

Sponsored

Looking for dealmaking and networking Sign Up


opportunities for your tech startup?
SLINGSHOT 2021
Recommended by

Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on hr@javatpoint.com, to get more information about given services.

Website Designing
Website Development
Java Development
PHP Development
WordPress
Graphic Designing
Logo
Digital Marketing
On Page and Off Page SEO
PPC
Content Development
Corporate Training
Classroom and Online Training
Data Entry

Training For College Campus


JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at hr@javatpoint.com.
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter

LEARN TUTORIALS OUR WEBSITES OUR SERVICES CONTACT

Learn Java Javatpoint.com Website Development Address: G-13, 2nd Floor, Sec-3
Learn Data Structures Hindi100.com Android Development Noida, UP, 201301, India
Learn C Programming Lyricsia.com
Website Designing Contact No: 0120-4256464, 9990449935
Learn C++ Tutorial Quoteperson.com
Learn C# Tutorial Jobandplacement.com Digital Marketing Contact Us
Learn PHP Tutorial Summer Training Subscribe Us
Learn HTML Tutorial Privacy Policy
Industrial Training
Learn JavaScript Tutorial Sitemap
Learn jQuery Tutorial College Campus Training
Learn Spring Tutorial About Me

© Copyright 2011-2021 www.javatpoint.com. All rights reserved. Developed by JavaTpoint.

You might also like