简体   繁体   English

类型不匹配。 必需:数组 <Uri> ! 找到:数组 <Uri?>

[英]Type mismatch. Required: Array<Uri>! Found: Array<Uri?>

The ? ? and !! !! syntax is very confusing in kotlin! 语法在kotlin中非常令人困惑! I'm declaring a value callback as a private member of my activity: 我将值回调声明为活动的私有成员:

private lateinit var mFilePathCallback: ValueCallback<Array<Uri>>

And I assign it on onShowFileChooser on onCreate method like so: 然后在onCreate方法的onShowFileChooser上分配它, onShowFileChooser所示:

    override fun onShowFileChooser(
    webView: WebView?,
    filePathCallback: ValueCallback<Array<Uri>>?,
    fileChooserParams: FileChooserParams?
): Boolean {
    mFilePathCallback = filePathCallback!! //Assigned here
    val intent = Intent(Intent.ACTION_GET_CONTENT)
    intent.type = "image/*"
    val PICKFILE_REQUEST_CODE = 100
    startActivityForResult(intent, PICKFILE_REQUEST_CODE)
    return true
}

But when I try to use it in onActivityResult like this: 但是当我尝试像这样在onActivityResult使用它时:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if(data != null && resultCode == Activity.RESULT_OK) {
        val resultsArray = arrayOfNulls<Uri>(1)
        resultsArray[0] = data.data
        mFilePathCallback.onReceiveValue(resultsArray)
        Log.d("ACTIVITY RESULT", data.data.toString())
    } else {
        Log.d("ACTIVITY RESULT", "Cannot get file path.")
    }
}

I get the following error in onRecieveValue function call: Type mismatch. Required: Array<Uri>! Found: Array<Uri?> 我在onRecieveValue函数调用中收到以下错误: Type mismatch. Required: Array<Uri>! Found: Array<Uri?> Type mismatch. Required: Array<Uri>! Found: Array<Uri?> Type mismatch. Required: Array<Uri>! Found: Array<Uri?> This is so confusing! Type mismatch. Required: Array<Uri>! Found: Array<Uri?>这真令人困惑!

  1. arrayOfNulls<Uri>(1) returns Array<Uri?> because its elements can be null and are null to start with. arrayOfNulls<Uri>(1)返回Array<Uri?>因为其元素可以为null且以nu​​ll开头。

  2. Setting an element with resultsArray[0] = data.data doesn't change the type (why would it?). resultsArray[0] = data.data设置元素不会改变类型(为什么?)。

  3. So you are passing an Array<Uri?> to mFilePathCallback.onReceiveValue which expects an Array<Uri> (an array whose elements are all Uri which can't be null). 因此,您mFilePathCallback.onReceiveValue Array<Uri?>传递给mFilePathCallback.onReceiveValue ,它期望使用Array<Uri> (其元素均为Uri不能为null的数组)。

Instead of the cast as in your own answer, just create the array of the correct type to start with: 不用像您自己的答案那样进行强制类型转换,只需创建正确类型的数组以以下内容开头:

val uri = data.data
if (uri != null) {
    val resultsArray = arrayOf<Uri>(uri)
    mFilePathCallback.onReceiveValue(resultsArray)
    Log.d("ACTIVITY RESULT", uri.toString()) // why toString?
} else {
    // your original code doesn't cover this case
    // so decide what to do here
}

Note that if you just do 请注意,如果您只是这样做

val resultsArray = arrayOf<Uri>(data.data)

you should ideally get a warning because data.data can be null, but it doesn't seem to be properly marked as @Nullable . 理想情况下,您应该收到警告,因为data.data可以为null,但似乎未正确标记为@Nullable

Kotlin is very strict on types. Kotlin对类型非常严格。 As Alexey Romanov already mentioned , when you create an array with arrayOfNulls , that creates an Array<Uri?> . Alexey Romanov所述 ,当您使用arrayOfNulls创建数组时,将创建Array<Uri?>

A nullable type can contain the type itself, but a non-null type cannot contain null. 可为null的类型可以包含该类型本身,但非null类型不能包含null。 Conversion from Array<Uri> to Array<Uri>? Array<Uri>转换为Array<Uri>? is fine for an instance. 对于一个实例来说还可以。 However, due to variance in generics, you can't pass Array<Uri> as an argument of the type Array<Uri?> . 但是,由于泛型中的差异,您不能将Array<Uri>作为Array<Uri?>类型的参数传递。 More on that here . 这里更多。

You need an Array<Uri>! 您需要一个Array<Uri>! . The ! ! is a special syntax you can't use, but that indicates a platform call to a method with either a return type or argument with an undefined nullability type. 是您无法使用的特殊语法,但是它表示平台调用具有返回类型或具有未定义可空性类型的参数的方法。 What's important to keep in mind here is that you can pass a non-null type to it, or a nullable one for that matter. 这里要记住的重要一点是,您可以将非null类型传递给它,或者将null传递给该类型。 ! just means the compiler doesn't know, so it doesn't strictly enforce null-safety in the same way as it usually would. 只是意味着编译器不知道,因此它没有严格按照通常的方式强制执行null安全性。

For an instance, this method: 对于一个实例,此方法:

public void someMethod(String str) {}

Will have the str parameter interpreted as a String! str参数解释为String! in Kotlin. 在科特林。 Add @Nullable and it's String? 添加@Nullable ,它是String? , or @NonNull and it's String . @NonNull ,它是String

The key point, as outlined in the previous link, the method is interpreted as a potentially nullable array of non-null URIs: 如上一链接所述,关键点是该方法被解释为可能为空的非null URI数组:

Array   <Uri>                            !
^ Type  ^ Generic type (here: non-null)  ^ signifies the type (NOT the generic type) is potentially nullable (not normally useable)

Anyway, the main issue here is that you're trying to pass Array<Uri> to Array<Uri?> - as outlined in the post I linked earlier, if you want to support that, you need to add out Uri? 无论如何,这里的主要问题是您试图将Array<Uri>传递给Array<Uri?> -如我之前链接的文章中所述,如果要支持该功能,您需要添加out Uri? as the parameter. 作为参数。 The method being a part of the stdlib means you can't do that. 该方法是stdlib的一部分,意味着您不能这样做。

If you're completely sure you'll never get a null type in the array after it's populated, you can, as you outlined in your answer, cast it. 如果您完全确定在填充数组后再也不会得到null类型,则可以按照答案中的概述进行强制转换。 That being said, I'd highly recommend you use the safe cast operator in combination with let to avoid a crash if you get null. 话虽如此,我强烈建议您将安全的强制转换运算符与let结合使用,以免在您得到null时崩溃。 In case you didn't check, that can happen : 如果您没有检查, 可能会发生这种情况

 Returns URI The URI of the data this intent is targeting or null. 

You can go with something like Alexey Romanov mentioned - Run an if-else statement to check if data is null, and put it directly into an array using arrayOf if it isn't null. 您可以使用提到的Alexey Romanov之类的东西-运行if-else语句以检查数据是否为空,如果数据不为空,则使用arrayOf将其直接放入数组。 That being said, you should still handle getData() returning null, even if you go with the as approach. 话虽如此,即使您使用as方法,仍应处理getData()返回null的问题。

The ? ? and !! !! syntax is very confusing in kotlin! 语法在kotlin中非常令人困惑!

They are not Confusion both Symbol have different Meaning Kotlin. 它们不是混淆,两个符号都有不同的含义Kotlin。

To Explain Both Symbol : 解释两个符号:

Lets Take : 让我们来 :

Symbol ? 符号 and it known as Safe Nullable cast operator 它被称为安全可空强制转换运算符

This Symbol work as Nullable. 此符号可为空。 Means when you try to assign Value in Kotlin 表示当您尝试在Kotlin中分配值时

val myString : String? = null

and Difference 与差异

val myString : String = null // This will give Error So you have to put string with null value (e.g.[""]).

and The Other Symbol !! 和另一个符号 and it is called as Null Safety : 它被称为空安全性

It means Not Nullable. 这意味着不可为空。

When you pass have to Pass Value according to it's datatype. 传递时,必须根据其数据类型传递值。 Means if it asks for string you have to pass String. 表示是否要求输入字符串,您必须传递String。

But when it receives null value or wrong response. 但是当它收到空值或错误的响应时。

Then it will give you 那会给你

NullPointerException 空指针异常

If you have any query then just comment it down i'll clear for you. 如果您有任何疑问,只需将其注释掉,我会为您清除。

我要做的就是将结果数组转换为Array<Uri>

mFilePathCallback.onReceiveValue(resultsArray as Array<Uri>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型不匹配。 必需:片段,找到:PlaceAutocompleteFragment - Type mismatch. Required: Fragment, Found: PlaceAutocompleteFragment 类型不匹配。 要求:观察员<in Int!>成立:? - Type mismatch. Required: Observer<in Int!> Found:? 类型不匹配。 必需:找不到:回调&lt;*&gt; - Type mismatch. Required: Nothing Found: Callback<*> 类型不匹配。 必需:找到的上下文:在片段中 - Type mismatch. Required: Context Found: In Fragment 类型不匹配。 要求:找到的上下文:意图 - Type mismatch. Required: Context Found: Intent 类型不匹配。 必需:ContentResolver! 找到:整数 - Type mismatch. Required: ContentResolver! Found: Int 所需类型 Uri 找到 Uri? - required type Uri found Uri? Kotlin无法获得类型干扰所需的数组 <Uri> ! 找到数组 <Uri?> - Kotlin not able to get type interference required Array<Uri>! found Array<Uri?> 类型不匹配。 必需:结果<newsresponse> : 发现: 结果<response<newsresponse> &gt;? </response<newsresponse></newsresponse> - Type mismatch. Required: Result<NewsResponse>! Found: Result<Response<NewsResponse>>? 类型不匹配。 必需:FirebaseRecyclerAdapter<chatobject, chatvoiceviewholders> ? 成立:</chatobject,> - Type mismatch. Required: FirebaseRecyclerAdapter<ChatObject, ChatVoiceViewHolders>? Found:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM