使用通用参数创建重复操作的方法

时间:2017-12-12 22:08:05

标签: android performance kotlin generic-programming

我的代码有以下方法:

fun saveArticles(data: JSONArray) {
    var active = String()
    for (i in 0..data.length().minus(1)) // create string

    val articles = Select.from(Article::class.java).list()

    val iterator = articles.iterator()
    while (iterator.hasNext()) {
        val article = iterator.next() as Article
        if (!active.contains(Regex(article.id.toString()))) article.delete()
    }
}

fun saveDossiers(data: JSONArray) {
    var active = String()
    for (i in 0..data.length().minus(1)) // create string

    val dossiers = Select.from(Dossier::class.java).list()

    val iterator = dossiers.iterator()
    while (iterator.hasNext()) {
        val dossier = iterator.next() as Dossier
        if (!active.contains(Regex(dossier.id.toString()))) dossier.delete()
    }
}

fun saveVideos(data: JSONArray) {
    var active = String()
    for (i in 0..data.length().minus(1)) // create string

    val videos = Select.from(Video::class.java).list()

    val iterator = videos.iterator()
    while (iterator.hasNext()) {
        val video = iterator.next() as Video
        if (!active.contains(Regex(video.id.toString()))) video.delete()
    }
}

如您所见,所有方法都完全相同。唯一的区别是我目前正在工作的对象的类型。我可以以某种方式创建一个具有类型参数的单个方法,并根据类型更改我需要工作的类吗?像这样:

fun saveVideos(data: JSONArray, type: Class) {
    var active = String()
    for (i in 0..data.length().minus(1)) // create string

    val list = Select.from(type).list()

    val iterator = list.iterator()
    while (iterator.hasNext()) {
        val item = iterator.next() as type
        if (!active.contains(Regex((item as type).id.toString()))) item.delete()
    }
}

1 个答案:

答案 0 :(得分:1)

您需要提取界面并使用interface Blabla { fun delete() val id: Int } inline fun <reified T : Blabla>saveVideos(data: JSONArray) { var active = String() for (i in 0..data.length().minus(1)) // create string val list = Select.from(T::class.java).list() val iterator = list.iterator() while (iterator.hasNext()) { val item = iterator.next() as T if (Regex(item.id.toString()) !in active) item.delete() } } 通用。

inline fun <reified T : Blabla>saveVideos(data: JSONArray) {
    val active = ""
    for (i in 0 until data.length()) {} // create string

    val list = Select.from(T::class.java).list()

    list
            .map { it as T }
            .filter { Regex(it.id.toString()) !in active }
            .forEach { it.delete() }
}

这应该有用。

另外,我强烈建议您使用Kotlin集合库,如下所示。

forEach { it.delete() }

您甚至可以用forEach(T::delete)

替换arr = [i for i in range(10)]