How do I convert Array <T?>? in Array <T> in Kotlin

I am taking my first steps in Kotlin and trying to write a simple string splitting function. I started with this:

fun splitCSV(s : String) : Array<String> {
    return s.split(",");
}

      

Which I think could also be written like this:

fun splitCSV(s : String) : Array<String> = s.split(",");

      

But I am getting a type error since s.split is returning Array<String?>?

, not Array<String>

. I couldn't find an easy way to do the cast, so I wrote this function to convert:

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, I am now getting a runtime error:

ClassCastException: [Ljava.lang.Object; cannot be applied to [Ljava.lang.String

If I change T in forceNotNull

to String then it works, so I think I am close to a solution.

Is it correct? And if so, how can I fix it forceNotNull

to work in general?

+3


source to share


1 answer


Not sure if this is the best method, but this works:

fun splitCSV(s : String) : Array<String> {
  return ( s.split(",") as? Array<String>? ).sure() ;
}

      

While IntelliJ highlights as?

with "This spell will never succeed" ... So my initial optimism fades away

Oddly enough, it looks like it works ...

Like:

fun splitCSV(s : String) : Array<String> {
  return s.split(",").sure() as Array<String> ;
}

      



But with the same warning ... I'm confused, so I'll stop now: - /

Edit

You can of course make it work with List<String>

:

import java.util.List

fun splitCSV(s : String) : List<String> {
  return s.split(",")!!.map<String?,String> { it!! }
}

      

but that's not the question :-)

+1


source







All Articles