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?