Android Kotlin Dagger2提供了gson:指定为非null的参数为null

我想提供一个单一的gson实例,所以我提供它在我的NetworkModule,当我创建改造api,gson是非null,但是当我在改造类中使用gson实例,它是空的..

@Module class NetworkModule { @Provides @Singleton fun provideGson(): Gson { return Gson() } @Provides @Singleton fun provideMyEnterpriseApi(gson: Gson): MyEnterpriseApi { //HERE GSON IS NOT NULL return RetrofitMyEnterpriseApi(BuildConfig.API_MYENTERPRISE_URL, BuildConfig.API_MYENTERPRISE_CONNECTION_TIMEOUT, BuildConfig.API_MYENTERPRISE_READ_TIMEOUT, gson) } } 

我的翻新API类:

 class RetrofitMyEnterpriseApi(baseUrl: String, connectTimeout: Long, readTimeout: Long, private val gson: Gson) : RetrofitApi(baseUrl, connectTimeout, readTimeout, RetrofitMyEnterpriseCalls::class.java) { override fun buildRetrofit(baseUrl: String, connectTimeout: Long, readTimeout: Long): Retrofit { val builder = Retrofit.Builder() builder.baseUrl(baseUrl) builder.client(buildClient(connectTimeout, readTimeout)) builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) builder.addConverterFactory(GsonConverterFactory.create(gson)) return builder.build() } private fun buildClient(connectTimeout: Long, readTimeout: Long): OkHttpClient { //HERE GSON IS NULL return OkHttpClient.Builder() .addInterceptor(OAuth2Interceptor(gson, this)) .addInterceptor(LoggingInterceptor.newInstance()) .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS) .readTimeout(readTimeout, TimeUnit.MILLISECONDS) .build() } } 

RetrofitApi类:

 abstract class RetrofitApi (baseUrl: String, connectTimeout: Long, readTimeout: Long, callsClass: Class) { protected val calls: C init { val retrofit = buildRetrofit(baseUrl, connectTimeout, readTimeout) calls = retrofit.create(callsClass) } protected abstract fun buildRetrofit(baseUrl: String, connectTimeout: Long, readTimeout: Long): Retrofit } 

所以,当我提供它不是null,但是当我在buildClient方法中使用它是null,我不明白为什么,我错过了Kotlin的东西也许。

    我发现答案时,我张贴\ o /

    所以问题是RetrofitMyEnterpriseApi类中的gson字段是在RetrofitApi父类的init之后instancied,我认为这很奇怪,因为我通过它参数,但..

    我只需要在RetrofitMyEnterpriseApi类的init之后调用我的buildRetrofit方法,或者将gson实例发送给我的父类。