-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.kt
More file actions
54 lines (49 loc) · 1.23 KB
/
Copy pathApp.kt
File metadata and controls
54 lines (49 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package dslSimple
// https://dzone.com/articles/kotlin-dsl-basics
class Employee(
var name: String = "",
var age: Int = 0
) {
override fun toString(): String {
return "Employee(name='$name', age=$age)}"
}
}
/*
* function that accepts a lambda as a receiver
* */
fun employee(action: Employee.() -> Unit): Employee {
val employee = Employee()
employee.action()
return employee
}
/*
* Class that implements operator invoke that gets called when you use the class instance as a function
* */
class Address(
var street: String = "",
var building: String = ""
) {
operator fun invoke(action: Address.() -> Unit): Address {
println("Invoke called")
this.action()
return this
}
override fun toString(): String {
return "Address(street='$street', building='$building')"
}
}
fun main() {
// using the employee function to create an instance of the employee
val emp = employee {
age = 25
name = "Adil Shaikh"
}
println(emp.toString())
// using the class invoke function, which is a call without the method name
val address = Address()
address {
street = "Super road"
building = "Jupiter"
}
println(address)
}