Created
August 20, 2018 11:51
-
-
Save AlexJuca/449455f410334141b2f87841e5dc2d10 to your computer and use it in GitHub Desktop.
Kotlin Observer Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.properties.Delegates | |
fun main(args: Array<String>) { | |
val kumbu = Wallet(0) | |
kumbu.listener = AccountChangedListener() | |
println("Saldo geral: ${kumbu.balance}") | |
kumbu.premiumAccount = true | |
println(kumbu.premiumAccount) | |
kumbu.premiumAccount = false | |
} | |
interface AccountTypeChangedListener { | |
fun onChange(account: Boolean, wallet: Wallet) | |
} | |
class AccountChangedListener: AccountTypeChangedListener { | |
override fun onChange(account: Boolean, wallet: Wallet) { | |
when(account) { | |
true -> wallet.balance += 100 false -> wallet.balance = wallet.balance - 100 | |
} | |
} | |
} | |
class Wallet(var balance: Int = 0) { | |
var listener : AccountTypeChangedListener? = null | |
var premiumAccount: Boolean by Delegates.observable(false) { | |
_, _, new -> | |
listener?.onChange(new, this) | |
println("Saldo geral: ${this.balance}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment