隐式 属性 类型与显式 属性 类型相同吗?
Is an implicit property type same with an explicit property type?
以下代码 A 来自 Kotlin-for-Android-Developers。代码B是我写的
这两个不同的代码块功能是否相同?
代码A
class DetailActivity : AppCompatActivity(), ToolbarManager {
override val toolbar by lazy { find<Toolbar>(R.id.toolbar) }
...
}
代码B
class DetailActivity : AppCompatActivity(), ToolbarManager {
override val toolbar: Toolbar by lazy { find<Toolbar>(R.id.toolbar) }
...
}
从结构来看,它们是一样的。 Kotlin 编译器将发出与源代码相同的 java 字节代码,如下所示:
private final Lazy<Toolbar> toolbarProvider = lazy(()-> find(R.id.toolbar));
public Toolbar getToolbar(){
return toolbarProvider.getValue();
}
属性 类型在上面的 代码 B 中是可选的,但在通过接口而不是实现编程时它很有用 [1],如果实现是changed 唯一需要改变的是实例化的地方,因为 toolbar
的使用根本无法访问其子 类 声明的功能。例如:
//declare as abstract supertype ---v
override val toolbar: AbstractToolbar by lazy { find<Toolbar>(R.id.toolbar) }
// ^
//when implementation was changed only need to change here.
//e.g:change the `Toolbar` to other subtype of AbstractToolbar: find<MiniToolbar>()
从编译器的角度来看,它们是不同的。由于编译器会在编译时推断 代码 A 中的实际 属性 类型,例如:
// v--- the property type `Toolbar` is inferred at compile-time
override val toolbar/*:Toolbar*/ by lazy { find<Toolbar>(R.id.toolbar) }
[1]: https://en.wikipedia.org/wiki/Liskov_substitution_principle
以下代码 A 来自 Kotlin-for-Android-Developers。代码B是我写的
这两个不同的代码块功能是否相同?
代码A
class DetailActivity : AppCompatActivity(), ToolbarManager {
override val toolbar by lazy { find<Toolbar>(R.id.toolbar) }
...
}
代码B
class DetailActivity : AppCompatActivity(), ToolbarManager {
override val toolbar: Toolbar by lazy { find<Toolbar>(R.id.toolbar) }
...
}
从结构来看,它们是一样的。 Kotlin 编译器将发出与源代码相同的 java 字节代码,如下所示:
private final Lazy<Toolbar> toolbarProvider = lazy(()-> find(R.id.toolbar));
public Toolbar getToolbar(){
return toolbarProvider.getValue();
}
属性 类型在上面的 代码 B 中是可选的,但在通过接口而不是实现编程时它很有用 [1],如果实现是changed 唯一需要改变的是实例化的地方,因为 toolbar
的使用根本无法访问其子 类 声明的功能。例如:
//declare as abstract supertype ---v
override val toolbar: AbstractToolbar by lazy { find<Toolbar>(R.id.toolbar) }
// ^
//when implementation was changed only need to change here.
//e.g:change the `Toolbar` to other subtype of AbstractToolbar: find<MiniToolbar>()
从编译器的角度来看,它们是不同的。由于编译器会在编译时推断 代码 A 中的实际 属性 类型,例如:
// v--- the property type `Toolbar` is inferred at compile-time
override val toolbar/*:Toolbar*/ by lazy { find<Toolbar>(R.id.toolbar) }
[1]: https://en.wikipedia.org/wiki/Liskov_substitution_principle