Migrate Web Service API from Java to Kotlin
interface
public interface ArticlesServiceApi {
@GET("demo-articles.json")
LiveData<ApiResponse<List<Article>>> getArticles();
}
// 1
interface ArticlesServiceApi {
@get:GET("demo-articles.json")
val articles: LiveData<ApiResponse<List<Article>>>
}
// 2
interface ArticlesServiceApi {
@GET("demo-articles.json")
fun getArticles(): LiveData<ApiResponse<List<Article>>>
}
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
class WebServiceGenerator
工作正常,但自动转成 Kotlin 代码后就出现了这个问题,问题出在这个方法,目前不清楚原因 TODO,所以暂时没有把这个Java类转成Kotlin:
@Provides
@Singleton
fun provideGson(articlesDeserializer: ArticlesDeserializer,
articleDeserializer: ArticleDeserializer): Gson {
val articleType = object : TypeToken<List<Article>>() {}.type
return GsonBuilder()
.setLenient()
.registerTypeAdapter(Article::class.java, articleDeserializer)
.registerTypeAdapter(articleType, articlesDeserializer)
.create()
}
The spread operator (*) is used to pass an array when vararg arguments are expected
Java codes:
@Override
protected void saveCallResult(@NonNull List<Article> articles) {
mArticlesDao.bulkInsert(articles.toArray(new Article[articles.size()]));
}
Kotlin codes:
override fun saveCallResult(articles: List<Article>) {
mArticlesDao.bulkInsert(*articles.toTypedArray())
}
2018-08-27 Weiyi Li