简体   繁体   English

我该怎么做:输入扩展名 Arraylist

[英]How I can do it: typed Extension for Arraylist

I try it:我试试看:

fun <T : E> ArrayList<E>.getTypeOrNull(index:Int) : T? {
  val item = this.getOrNull(index)
  return if(item is T) item else null
}

How I can do it?我该怎么做? I am newb on kotlin java我是 kotlin java 的新手

do you really need an extension for it?你真的需要扩展吗? To call the extension you have to pass the concrete type of T right?要调用扩展程序,您必须传递T的具体类型,对吗? Otherwise, he function doesn't know which type to check.不然他function不知道查哪个类型。

How about simply:怎么样简单:

yourResult = yourList[5] as? ConcreteT

I think you have to check requirements because the function seems strange:我认为您必须检查要求,因为 function 看起来很奇怪:

But if you really need it:但如果你真的需要它:

inline fun <TE : Any, reified T: TE> ArrayList<TE>.getTypeOrNull(index:Int) : T? =
    getOrNull(index) as? T

and now you can use it:现在你可以使用它了:

fun test() {
    val list = ArrayList<CharSequence>()
    val str: String? = list.getTypeOrNull(5)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM