How to convert Array<T?>? into Array<T> in Kotlin
Question
I'm taking my first steps in Kotlin, and trying to write a simple string split function. I started with this:
fun splitCSV(s : String) : Array<String> {
return s.split(",");
}
Which I guess can be also written like this:
fun splitCSV(s : String) : Array<String> = s.split(",");
But I'm getting a type error, since s.split returns an Array<String?>?
and not Array<String>
. I couldn't find a simple way to do a cast, so I wrote this function to do the conversion:
fun forceNotNull<T>(a : Array<T?>?) : Array<T> {
return Array<T>(a!!.size, { i -> a!![i]!! });
}
fun splitCSV(s : String) : Array<String> = forceNotNull(s.split(","));
However, now I'm getting a runtime error:
ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String
If I change T in forceNotNull
to String, then it works, so I guess I'm close to a solution.
Is this the right way to go about it? And if it is, how can I fix forceNotNull
to work in the generic case?
Solution
Not sure it's the best method, but this seems to work:
fun splitCSV(s : String) : Array<String> {
return ( s.split(",") as? Array<String>? ).sure() ;
}
Although IntelliJ highlights the as?
with "This cast can never succeed"... So my initial optimism is fading
Oddly though, it seems to work...
As does:
fun splitCSV(s : String) : Array<String> {
return s.split(",").sure() as Array<String> ;
}
But with the same warning... I'm getting confused, so I'll stop now :-/
Edit
Of course, you can get it to work with List<String>
:
import java.util.List
fun splitCSV(s : String) : List<String> {
return s.split(",")!!.map<String?,String> { it!! }
}
but that wasn't the question ;-)