-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhigherOrder.kt
More file actions
53 lines (47 loc) · 1.5 KB
/
higherOrder.kt
File metadata and controls
53 lines (47 loc) · 1.5 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
/**
** Higher-Order Function as parameter to a class.
** Robert Linnemann
** https://ios.robertlinnemann.com
**/
fun main(args: Array<String>) {
//make an object that makes an internal object.
val m = Master()
//call a function on the internal object that then calls
//through to the lamda function that was passed into it.
m.apprentice?.sendMessageThroughLambda()
//A similar was to pass a message to a parent object would be to
//use an interface
m.apprentice?.sendMessageThroughInterface()
}
interface PassMessageListener {
fun message(message: String)
}
class Master: PassMessageListener {
var apprentice: Apprentice?
init {
//pass in the function print to the Apprentice object.
apprentice = Apprentice(::print)
//setup the interface listener
apprentice?.passMessageListener = this
}
fun print(message: String) {
println(message)
}
//interface method
override fun message(message: String) {
print(message)
}
}
//This gets a function passed in as the variable 'send'.
class Apprentice(send: (String) -> Unit) {
val send = send
var passMessageListener: PassMessageListener? = null
fun sendMessageThroughLambda() {
//sends directly to the function on a whole 'notha level
send("Print this for me.")
}
fun sendMessageThroughInterface() {
//traditional interface way to pass a message
passMessageListener?.message("Print this for you")
}
}