Hey! New to Kotlin and this group and struggling t...
# announcements
t
Hey! New to Kotlin and this group and struggling to get an answer for how to use callback in the form of optional property. For example:
Copy code
var onDownloadCompleted: ((data: ByteArray) -> Unit)? = null
Coming from Swift, I tried calling it using ? mark but it yields compiler error “(Error:(108, 26) Unexpected tokens (use ‘;’ to separate expressions on the same line)“:
Copy code
onDownloadCompleted?(bytes)
So currently I’m using longer form which works:
Copy code
if (onDownloadCompleted != null) {
    onDownloadCompleted!!(bytes)
}
But it feels so un-DRY for such a simple task, is there a simpler way? Or am I thinking in wrong direction and should use different callback approach?
e
You could try using the
invoke
eg.
Copy code
onDownloadCompleted?.invoke(bytes)
👍🏼 5
t
Allright, this works! Thanks!!!
m
You shouldn't need
!!
when you do the null-check btw. The variable gets smart casted to the non-nullable type.
k
not if it's a
var
property
m
Oh, true
r
Remove .invoke you dont need extra code.
m
@radityagumay
invoke
is the whole point with the answer. You can't do
onDownloadCompleted?(bytes)
.
r
Ah, yes. Because this expect nullable.