Kotlin: Funtional type mismatch

When compiling, I am getting below error:

Type mismatch: inferred type is (String, Boolean) → Any, but ((String, Boolean) → Unit)? expected

My Type Declaration

private val ConsisFilter_Click = { filterText: String, isStrictSearch: Boolean ->

    try {
        //My Codes
    }
    catch (e: Exception) {
        try {
            alert{}.show()
        }catch (ignored: Exception) {}
    }
}



var ConsisFilterClickEvent:((filterText: String, isStrictSearch: Boolean) -> Unit)? = null 

      

assigninkg like this

inputDialog!!.ConsisFilterClickEvent = ConsisFilter_Click

      

I follow the same pattern elsewhere, but I don't get any error. Only this particular detail gives problems. I am doing something wrong. Please help me.

NOTE: If I put all codes ConsisFilter_Click

(try catch block code) in a separate function and just call that function from ConsisFilter_Click

, then it all works well

thank

+3


source to share


2 answers


you cannot assign to a ConsisFilter_Click

variable ConsisFilterClickEvent

as its an implicit type (String, Boolean) -> Any

, not (String, Boolean) -> Unit

. because of the return type of catch-block Unit

, but the return type of the last try-block statement is not Unit

, which will make the return type lambda before Any

unless you use an explicit type variable.

you must explicitly define the type of the variable ConsisFilter_Click

as shown below:



val ConsisFilter_Click: (filterText: String, isStrictSearch: Boolean) -> Unit  = {
    filterText: String, isStrictSearch: Boolean ->

    try {
        //My Codes
    }
    catch (e: Exception) {
        try {
            alert{}.show()
        }catch (ignored: Exception) {}
    }
}

      

+3


source


When using a lambda in Kotlin, if the return type is not Unit

, the last expression in it is returned . In your case, this is a try-catch statement, which also works like an expression in Kotlin.

If you want your lambda return type to be Unit

, you can explicitly write its type as mentioned in another answer, or you can assign it directly ConsisFilterClickEvent

instead of storing it in another variable first - in both of these cases, the compiler will figure out that you don't want to return your last expression, and just want to use try-catch as a statement.



Another thing you can do is explicitly return an object Unit

at the end of your lambda:

private val ConsisFilter_Click = { filterText: String, isStrictSearch: Boolean ->
    try {
        ...
    }
    catch (e: Exception) {
        ...
    }
    Unit
}

      

+4


source







All Articles