Android Weekly Notes #439

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容