Reputation: 755
I'm getting below error while compiling:
Type mismatch: inferred type is (String, Boolean) -> Any but ((String, Boolean) -> Unit)? was expected
My Type Declaration is
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'm following same pattern elsewhere but not getting any error. Only this particular piece is giving problem. Am I doing something wrong. Please help me.
NOTE: If I put all codes of ConsisFilter_Click
(code of try catch block) into a separate function and simply call that function from ConsisFilter_Click
then every this works well
Thanks
Upvotes: 3
Views: 5280
Reputation: 89538
When using a lambda in Kotlin, if the inferred return type is not Unit
, the last expression in it is returned. In your case, this is the try-catch statement, which also works as an expression in Kotlin.
If you want to force your lambda's return type to be Unit
, you can either write down its type explicitly as stated in the other answer, or you can directly assign it to 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 to explicitly return the Unit
object at the end of your lambda:
private val ConsisFilter_Click = { filterText: String, isStrictSearch: Boolean ->
try {
...
}
catch (e: Exception) {
...
}
Unit
}
Upvotes: 5
Reputation: 30676
you can't assign ConsisFilter_Click
to the variable ConsisFilterClickEvent
since its implicit type is (String, Boolean) -> Any
rather than (String, Boolean) -> Unit
. due to the return type of the catch-block is Unit
but the return type of the last statement of the try-block is not Unit
, that will makes the lambda's return type to Any
if you don't using an explicit type variable.
you must define the type of the variable ConsisFilter_Click
explicitly as 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) {}
}
}
Upvotes: 3