gradle 修改
加入 kotlin 之后需要使用 kapt,gradle 修改为
//kotlin
//dagger
compile "com.google.dagger:dagger:$rootProject.daggerVersion"
compile "com.google.dagger:dagger-android:$rootProject.daggerVersion"
compile "com.google.dagger:dagger-android-support:$rootProject.daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$rootProject.daggerVersion"
kapt "com.google.dagger:dagger-compiler:$rootProject.daggerVersion"
compile "com.blankj:utilcode:$rootProject.androidUtilsVerson"
//不加无法编译通过
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$rootProject.kotlin_version"
project gradle
buildscript {
ext.kotlin_version = '1.1.51'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
可以使用 AS 3.0 的新功能 或者 kotlin 插件,将项目整个工程转为 kotlin
注意,有几处 需要手动修改
定义的dagger注解
@Scope
@kotlin.annotation.Retention
annotation class ActivityScoped
@Scope
@kotlin.annotation.Retention
annotation class FragmentScoped
注入使用
@Inject
lateinit var mPresenter: RegisterContract.Presenter
需要使用 lateinit
来表示延迟初始化
优化 mvp 结构
可以将在 Presenter 接口这持有 view (view 是abs),复写接口的时候复写改 view
interface BasePresenter<T> {
var mView:T?
/**
* Binds presenter with a view when resumed. The Presenter will perform initialization here.
*
* @param view the view associated with this presenter
*/
fun takeView(view: T){
mView = view
}
/**
* Drops the reference to the view when destroyed
*/
fun dropView(){
mView = null
}
}
并在takeView
dropView
对 view 进行复制,这样的好处就是复现该接口的同时就不用重复这些代码了 。而 java在接口也不能定义变量,在接口方法也也不能定义操作