package com.wustyq.kotlinstudy
import javax.security.auth.Subject
class MagicBox<T>(item: T) {
var available = false
private var subject: T = item
fun fetch(): T? {
return subject.takeIf { available }
}
fun <R> fetch(subjectModFunction: (T) -> R): R? {
return subjectModFunction(subject).takeIf { available }
}
}
class Boy(val name: String, val age: Int)
class Dog(val weight: Int)
fun main() {
val box1: MagicBox<Boy> = MagicBox(Boy("Jack", 20))
val box2: MagicBox<Dog> = MagicBox(Dog(20))
box1.available = true
println(box1.fetch()?.age)
val boy3 = box1.fetch {
Boy(it.name, it.age + 10)
}
println(boy3?.age)
}