-
Notifications
You must be signed in to change notification settings - Fork 1
/
Delegation.kt
32 lines (25 loc) · 828 Bytes
/
Delegation.kt
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
package com.arindam.kotlin.x
/**
* Prefer delegation over inheritance for code reuse.
* Kotlin makes it easier and has first-class support for delegation! 💪
*
* Created by Arindam Karmakar on 7/8/19.
*/
interface Publisher {
fun publish(message: String)
}
class FacebookPublisher : Publisher {
override fun publish(message: String) = println("Posting to wall...\n$message")
}
class TwitterPublisher : Publisher {
override fun publish(message: String) = println("Twitting...\n$message")
}
class SocialMediaManager(private val publisher: Publisher) : Publisher by publisher
fun main() {
SocialMediaManager(FacebookPublisher()).publish("Hello")
// > Posting to wall...
// Hello World!
SocialMediaManager(TwitterPublisher()).publish("World")
// > Twitting...
// Hello World!
}