Home > Mobile >  How I can do it: typed Extension for Arraylist
How I can do it: typed Extension for Arraylist

Time:01-26

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

CodePudding user response:

do you really need an extension for it? To call the extension you have to pass the concrete type of T right? Otherwise, he function doesn't know which type to check.

How about simply:

yourResult = yourList[5] as? ConcreteT

CodePudding user response:

I think you have to check requirements because the function seems strange:

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)
}
  • Related