为什么扩展功能在另一个模块中不可见?

Why extension function is not visible in another module?

我的 Android 项目有两个模块:

app
common

settings.gradle:

rootProject.name='My project'
include ':app'
include ':common'

在我的 build.gradle:

implementation project(':common')

在普通包中,我有 StringUtil.kt 和下一个扩展功能:

fun String.isEmailValid(): Boolean {
    return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}

并且在 this class 我可以像这样使用扩展函数:

val str = ""
str.isEmailValid()

但是在 app 模块中我有 class

class RegistrationViewModel(application: Application) : AndroidViewModel(application) {

  fun doClickRegistration(email: String?, password: String?, retypePassword: String?) {
        val str = ""
        str.isEmailValid()
    }
}

但现在我得到编译错误:

Unresolved reference: isEmailValid

If you do not specify any visibility modifier, public is used by default, which means that your declarations will be visible everywhere; (Source)

由于您没有向 isEmailValid 添加任何可见性修饰符,因此它被视为 public

请注意,必须导入扩展函数。

import com.your.package.path.isEmailValid

在您的应用中 build.gradle 添加:

implementation project(':common')