Updated March 31, 2023
Introduction to Kotlin apply
Kotlin apply is one of the default methods, and it is the scope function. It is also known as an extension function for performing the operations on the particular type, and it’s set the scope to the object a which the apply is also invoked. It will run the object reference into the any expression so that the returning value of the object reference is complete and makes it return an object reference on the completion of the template class, which always takes the lambda expressions on the scope of the classes its reference will be returned.
Syntax
In kotlin language, it has a lot of functions, classes, and other keywords for utilising the kotlin logic in the application. Like that, apply is one of the scope functions that can be used to configure the object once initialized and returns the object itself.
class name{
var vars:datatype;
fun demo(){
///methodname
---some logic codes depends on the requirement—
}
}
name().apply{
---some codes---
}.demo()
The above codes are the basic syntax for utilising the apply() method in the kotlin class object initialization and return type.
How does apply work in Kotlin?
The kotlin application has some default functions that can be used to approach the top-level site in the file. It is needed for to create the class in to hold the reference of that class method. Kotlin apply is one of the extension functions that can be used on any of the types it runs on the object reference that can be of receiver format into the expression, and it returns the object reference. The apply function is similar to the run functionality, and it is only in terms of referring to the context of the object using “this” and other keywords like “it” in providing the null safety checks.
Apply keyword used in many cases that can be used with various scenarios, and it should be returned with an instance of Intent and an Alert dialog, etc. When we add the specific attributes in the application to them, it can be improved approach from the code snippet helps avoid variable names. The redundancy it thereby enhancing the code readability and the principle of code cleaning. We can see the other keywords and similar methods like run that accepts the return statement whereas the apply that does not accept a return object.
Examples of Kotlin apply
Given below are the examples of Kotlin apply:
Example #1
Code:
class Firstclass {
infix fun demo(s: String) {
}
fun example() {
this demo "Please enter your input types"
demo("Sivaraman")
}
}
class Worker {
var workerName: String = ""
var workerID: Int = 0
fun workerDetails(){
var lst=ArrayList<String>()
lst.add("Employee Name is: XX, Employee ID is:001")
lst.add("Employee Name is: XA, Employee ID is:001\n")
lst.add("Employee Name is: YB, Employee ID is:002\n")
lst.add("Employee Name is: YC, Employee ID is:003\n")
for(x in lst)
print("The employee lists are iterated and please find your output results $x ")
}
}
fun main(args: Array<String>)
{
Worker().apply{
this.workerName = "First Employee is Sivaraman"
this.workerID = 52
}.workerDetails()
data class First(var inp1 : String, var inp2 : String,var inp3 : String)
var first = First("Welcome To My Domain its the first example that related to the kotlin apply() function","Have a nice day users","Please try again")
first.apply { this.inp3 = "Welcome To My Domain its the first example that related to the kotlin apply() function" }
println(first)
with(first)
{
inp1 = "Please enter your input types"
inp2 = "Please enter your input types"
}
println(first)
}
Output:
In the above example, we performed the employee details using the default methods.
Example #2
Code:
interface firstInterface {
val x : Int
val y : String
get() = "Welcome To My Domain its the second example that related to the kotlin also() method"
}
interface secondInterface {
fun Sample1(){
println("Your Sample1 Method")
}
}
class Second : firstInterface, secondInterface {
override val x : Int
get() = 52
override fun Sample1()
{
println("Have a Nice Day users please try again")
}
private val res = "firstInterface Second"
fun eg() = "This is the second we discussed regarding kotlin also() method"
}
class Business
{
var bName: String = ""
var GST: String = ""
var Location: String = ""
var year: Int = 0
fun enteredNewEmployees(bn: String, gst: String, loc: String, yr: Int) {
bName = bn
GST = gst
Location = loc
year = yr
println("Please see the below new business name: $bName")
println("Please see the Business id: $GST")
println("Your Location is: $Location")
println("The Cross year of the new business is : $year")
}
fun NewBusinessName(bn: String) {
this.bName = bn
}
}
fun main(args: Array<String>)
{
data class Car(var carName: String, var CarModel : String)
var nw = Car("Benz", "AMGE53")
nw.apply { CarModel = "RangeRover Evoque" }
println(nw)
nw.also { it.CarModel = "Audi A6" }
println(nw)
val ob = Second()
ob.Sample1()
var ob1 = Business()
var ob2 = Business()
ob1.enteredNewEmployees("VSR Garments", "33ACKPV67253278", "TUP", 1994)
ob2.NewBusinessName("Raman")
println("bName of the new Business: ${ob2.bName}")
val s = Second()
println(s)
println(s.eg())
}
Output:
In the second example, we used interfaces, classes, and scope methods like (), apply() to implement the application.
Example #3
Code:
fun main(args: Array<String>)
{
data class Third(var str1: String, var str2 : String)
var third = Third("Siva", "Raman")
println("Welcome To My domain its the third example that related to the kotlin apply() method")
third.apply { str2 = "Sivaraman" }
println(third)
third.also { it.str2 = "Dell" }
println(third)
with(third)
{
str1 = "Sivaraman is the Employee working in XX company"
str2 = "He is using the DELL Laptop which provided by his office"
}
}
Output:
In the final example, we used default methods like also(), apply(), and with() methods for to perform the user operations in the application.
Conclusion
In kotlin language has some default scope functions for performing the operations in the kotlin application. Moreover, it has some default extension functions for doing something with an object, and it returns the value. Also, if we need to perform some other operations on an object and it returns some other object, we can utilise it.
Recommended Articles
This is a guide to Kotlin apply. Here we discuss the introduction, syntax, and working of apply in Kotlin along with different examples for better understanding. You may also have a look at the following articles to learn more –