Android Weekly Issue #439
How to Make the Compiler Smarter
Contract:
fun foo(): Boolean {
contract {
// Effect
}
// Function body
}
可以用如下几种方法:
- returns(value)
- returnsNotNull()
- implies(booleanExpression)
- callsInPlace(lambda, kind)
Mastering API Visibility in Kotlin
在设计API的时候, 暴露的越少越好.
目的:
- Easier to maintain and change.
- Easier to learn.
- Harder to misuse.
internal
关键字标明模块内可见, 设计library的时候很有用.
测试的时候可以这样用:
@VisibleForTesting(otherwise = PRIVATE)
internal var state: State
kotlin的internal
对于Java来说其实是public. 但是用起来名字会比较古怪, 比如 an internal method called createEntity
will become something like createEntity$moduleName
(on Android, it’s also suffixed by the build variant in addition to the module name).
解决的方法可以有:
class Repository {
@JvmName("pleaseDoNotCallThisMethod")
internal fun createEntity() { ... }
}
或者:
class Repository {
@JvmSynthetic
internal fun createEntity() { ... }
}
因为Kotlin默认都是public的, 所以很容易忘了限制, Kotlin1.4开始有了Explicit API mode
强制给所有的声明都加上访问限定符.
有一个问题是public inline方法不能调用internal的方法.
解决的办法就是加上@PublishedApi
注解:
@PublishedApi
internal fun secretFunction() {
println("through the mountains")
}
public inline fun song() {
secretFunction()
}
fun clientCode() {
song() // ok
secretFunction() // e: Cannot access 'secretFunction': it is internal
}
可能你的库有多个module, 而你又不想暴露给外部世界core之类的module, 那么就要用到opt-in.
Full Text Search in Room Tutorial: Getting Started
Room数据库中的全文搜索.
View binding for the lazy
Kotlin delegation + view binding.
还有另一个文章讲View Binding的好处: 3 Major Benefits Of View Binding Android
Android library development - Modularization
SDK库开发的模块化.
Code
- Bundler Bundle相关的Extensions.
- Barista 让Espresso UI测试更好写.
- AffectedModuleDetector 显示出受影响的modules.
网友评论