-
get可见性必须和属性可见性一致, 不能定义public属性的get为private
-
set可见性不能大于属性的可见性, 不能定义private属性的set为public
lateinit
这玩意好像有坑,kotlin中的新玩意,大神都嫌弃它,我们可以了解一下,既然是坑我们不用去记住它,免得被坑。。
lazy
是比较推荐的延迟初始化方式,实际上它是一个属性代理
接口代理其实就是可以把一些没必要实现的接口方法隐藏起来不去实现,方便一些,而不用每一个接口都要写一下。其中
by
关键字右边的就是实际代理类对象,它是构造函数中的一个属性,by
关键字左边的是代理类对象实现的接口。
例子:
//超级数组 同时支持list和map接口,通过接口代理的方式不必实现list和map接口的所有方法
class SuperArray<E>(
private val list: MutableList<E?> = ArrayList(),
private val map: MutableMap<Any, E> = HashMap()
) : MutableList<E?> by list, MutableMap<Any, E> by map {
override fun isEmpty() = list.isEmpty() && map.isEmpty()
override val size: Int
get() = list.size + map.size
override fun clear() {
list.clear()
map.clear()
}
override operator fun set(index: Int, element: E?): E? {
if (list.size <= index) {
repeat(index - list.size + 1) {
list.add(null)
}
}
return list.set(index, element)
}
override fun toString(): String {
return """List: [$list]; Map: [$map]"""
}
}
fun main() {
val superArray = SuperArray<String>()
val superArray2 = SuperArray<String>()
superArray += "Hello"
superArray["Hello"] = "World"
superArray2[superArray] = "World"
superArray[1] = "world"
superArray[4] = "!!!"
println(superArray)
println(superArray2)
}
lazy
属性代理 代理了Person实例的firstName的getter
方法,实际是一个函数 传递一个lambda表达式
class Person(val name: String){
//lazy属性代理 代理了Person实例的firstName的getter方法
// 实际是一个函数 传递一个lambda表达式
val firstName by lazy {
name.split(" ")[0]
}
val lastName by lazy {
name.split(" ")[1]
}
}
observable代理属性,监听set值变化:
class StateManager {
//observable代理属性,监听set值变化
var state: Int by Delegates.observable(0) {
property, oldValue, newValue ->
println("State changed from $oldValue -> $newValue")
}
}
自定义代理属性:
class Foo {
val x: Int by X()
var y: Int by X()
}
class X {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return 2
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, i: Int) {
}
}
其中getValue和setValue方法的参数写法是固定的
调用:
fun main() {
val stateManager = StateManager()
stateManager.state = 3
stateManager.state = 4
println(Foo().x)
}
自定义实例:读取Config.properties中的配置项
Config.properties文件中一般是key-value的配置
author=xxxx
version=1.0
desc=This is a demo.
class PropertiesDelegate(private val path: String, private val defaultValue: String = “”){
private lateinit var url: URL
private val properties: Properties by lazy {
val prop = Properties()
url = try {
javaClass.getResourceAsStream(path).use {
prop.load(it)
}
javaClass.getResource(path)
} catch (e: Exception) {
try {
ClassLoader.getSystemClassLoader().getResourceAsStream(path).use {
prop.load(it)
}
ClassLoader.getSystemClassLoader().getResource(path)!!
} catch (e: Exception) {
FileInputStream(path).use {
prop.load(it)
}
URL("file://${File(path).canonicalPath}")
}
}
prop
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return properties.getProperty(property.name, defaultValue)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
properties.setProperty(property.name, value)
File(url.toURI()).outputStream().use {
properties.store(it, "Hello!!")
}
}
}
abstract class AbsProperties(path: String){
protected val prop = PropertiesDelegate(path)
}
class Config: AbsProperties(“Config.properties”){
var author by prop
var version by prop
var desc by prop
}
fun main() {
val config = Config()
println(config.author)
config.author = "Bennyhuo"
println(config.author)
}
其实主要还是实现`getValue`和`setValue`方法就可以,需要注意的是签名写法,`setValue`最后一个参数是设置的值的类型,而`getValue`的返回值就是对应获取的值的类型。
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
}
最后看一下学习需要的所有知识点的思维导图。在刚刚那份学习笔记里包含了下面知识点所有内容!文章里已经展示了部分!如果你正愁这块不知道如何学习或者想提升学习这块知识的学习效率,那么这份学习笔记绝对是你的秘密武器!
**[CodeChina开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》](https://codechina.csdn.net/m0_60958482/android_p7)**
![](https://img-blog.csdnimg.cn/img_convert/4d8000af8a54b290dff0f87b867978f7.png)
: String {
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
}
最后看一下学习需要的所有知识点的思维导图。在刚刚那份学习笔记里包含了下面知识点所有内容!文章里已经展示了部分!如果你正愁这块不知道如何学习或者想提升学习这块知识的学习效率,那么这份学习笔记绝对是你的秘密武器!
CodeChina开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》
[外链图片转存中…(img-lZwIkRGO-1630580154829)]