open class Supercomputer {
open val theAnswer: Long = 42
}
class AppleComputer : Supercomputer() {
override val theAnswer: Long = 1_800_275_2273
}
val db: Database by lazy { connectToDb() }
val Context.preferences: SharedPreferences
get() = PreferenceManager
.getDefaultSharedPreferences(this)
val Context.inflater: LayoutInflater
get() = getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val Context.notificationManager: NotificationManager
get() = getSystemService(Context.NOTIFICATION_SERVICE)
as NotificationManager
// 不要这样做!
val Tree<Int>.sum: Int
get() = when (this) {
is Leaf -> value
is Node -> left.sum + right.sum
}
fun Tree<Int>.sum(): Int = when (this) {
is Leaf -> value
is Node -> left.sum() + right.sum()
}
val s = (1..100).sum()
// 不要这么做!
class UserIncorrect {
private var name: String = ""
fun getName() = name
fun setName(name: String) {
this.name = name
}
}
class UserCorrect {
var name: String = ""
}