如何转换Array< T?&gt ;?放入阵列T在科特林 [英] How to convert Array<T?>? into Array<T> in Kotlin

查看:69
本文介绍了如何转换Array< T?&gt ;?放入阵列T在科特林的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Kotlin迈出第一步,并尝试编写一个简单的字符串拆分函数.我从这里开始:

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(",");
}

我想也可以这样写:

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

但是我遇到类型错误,因为s.split返回Array<String?>?而不是Array<String>.我找不到一种简单的方法来进行转换,所以我编写了此函数来进行转换:

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;无法转换为[Ljava.lang.String

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

如果我将forceNotNull中的T更改为String,那么它将起作用,所以我想我已经接近解决方案了.

If I change T in forceNotNull to String, then it works, so I guess I'm close to a solution.

这是正确的做法吗?如果是的话,如何修复forceNotNull在一般情况下可以正常工作?

Is this the right way to go about it? And if it is, how can I fix forceNotNull to work in the generic case?

推荐答案

不确定这是最好的方法,但这似乎可行:

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() ;
}

尽管IntelliJ突出显示as?此强制转换永远不会成功" ...所以我最初的乐观情绪正在逐渐消失

Although IntelliJ highlights the as? with "This cast can never succeed"... So my initial optimism is fading

不过奇怪的是,它似乎可以工作...

Oddly though, it seems to work...

一样:

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 :-/

当然,您可以将其与List<String>一起使用:

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!! }
}

但这不是问题;-)

这篇关于如何转换Array&lt; T?&gt ;?放入阵列T在科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆