代码之家  ›  专栏  ›  技术社区  ›  Farid

用于返回具有指定类型的列表的Genric函数

  •  1
  • Farid  · 技术社区  · 6 年前

    下面的代码段返回类类型对象,因此不需要强制转换。

    fun <T: Any> getData(clazz: KClass<T>): T? {
    
    }
    
    // Calling function
    val article = getData(Article::class)
    article.read == true      // Call function is possible without casting
    

    现在我想做的是回来 List 具有特定的 Type 。但是 ::class 左边应该是唯一的班级我不能通过这样的考试 List<Article>::class

    如何解决这个问题?

    方法1。 创建扩展的类 List<Article> 并将该类作为参数传递

    class ArticleList: ArrayList<Article>
    
    
    fun <T: Any> getData(clazz: KClass<T>): T? {
    
    }
    
    // Calling function
    val articleList = getData(ArticleList::class)
    articleList[0].read == true      // Call function is possible without casting
    

    方法2。 更改的输入参数 getData() 功能到 类型 并在前面添加paramaterType getData() 函数,每次调用它时。

    fun <T: Any> getData(type: Type): T? {
    } 
    
    // Calling function
    val listType = object : TypeToken<ArrayList<Article>>() {}.type
    val data = getData<List<Article>>(listType)
    data[0].read == 1     // Call function is possible without casting
    

    目前,我正在努力避免 方法1 因为我最终会为每个项目创建一个类 方法2 已经是一种铸造。

    是否有其他最简单的解决方案?

    0 回复  |  直到 6 年前
        1
  •  2
  •   Andrei Tanana    6 年前

    顺便说一句,你可以使用 reified 类型参数 inline 不通过的函数 KClass 对象:

    inline fun <reified T> getData(): T? {
        // do something with T::class
    }
    

    这不是一个理想的解决方案,但您可以创建一个额外的 getDataList 功能:

    inline fun <reified T> getDataList(): List<T> {
        val listType = TypeToken.getParameterized(List::class.java, T::class.java)
        // do something
    }
    
        2
  •  0
  •   Rikesh Subedi    6 年前

    传递实际类型而不是类型参数的开销是多少?

    因为我也是科特林的新手。这是我想到的。

    class Article {
        var read = false
    }
    
    inline fun <reified T> getData() : T? {
        //how do I generically instantiate T, I don't have constructor info here
        for(con in T::class.java.constructors) {
            if(con.parameterCount == 0) {
                return con.newInstance() as T
            }
        }
        return null
    }
    fun main(){
        val article = getData<Article>() 
        article?.read = true
        var articleList = getData<ArrayList<Article>>() 
        article?.let{
            articleList?.add(it)
        }
        print(articleList)
    }