Reputation: 29342
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?
Upvotes: 4
Views: 2334
Reputation: 53
in Simple way you can cast string to Array in kotlin by:-
fun splitCSV(s: String) = s.split(",").toTypedArray()
call this function by
val array: Array<String> = splitCSV("ABC,XYZ,test,rupesh")
in kotlin CharSequence.split(regex) return List so if you want to change in type Array use .toTypedArray() method
Upvotes: 0
Reputation: 8355
Since the time of this post, kotlin has changed a lot and now there are lot easier and nice(explicit casts should be avoided) ways of converting Array<T?>?
to Array<T>
, one way would be to do
val data: Array<String?>? = getData()
val notNullArray: Array<String> = data?.filterNotNull()?.toTypedArray() ?: arrayOf()
here we make use of filterNotNull
to get a List<String>
and then convert that list to an Array<String>
, if however the original array is null
then we simply use arrayOf()
, which given us an empty Array<T>
?:
is the elvis
operator which returns the expression on its left if its not null otherwise it returns the value of expression on the right
Upvotes: 1
Reputation: 171194
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 :-/
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 ;-)
Upvotes: 1