https://kotlinlang.org logo
#announcements
Title
# announcements
t

Tomaz Kragelj

11/10/2017, 10:00 AM
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

everald

11/10/2017, 10:08 AM
You could try using the
invoke
eg.
Copy code
onDownloadCompleted?.invoke(bytes)
👍🏼 5
t

Tomaz Kragelj

11/10/2017, 10:32 AM
Allright, this works! Thanks!!!
m

marstran

11/10/2017, 11:39 AM
You shouldn't need
!!
when you do the null-check btw. The variable gets smart casted to the non-nullable type.
k

kirillrakhman

11/10/2017, 12:05 PM
not if it's a
var
property
m

marstran

11/10/2017, 12:06 PM
Oh, true
r

radityagumay

11/10/2017, 1:31 PM
Remove .invoke you dont need extra code.
m

marstran

11/10/2017, 1:33 PM
@radityagumay
invoke
is the whole point with the answer. You can't do
onDownloadCompleted?(bytes)
.
r

radityagumay

11/10/2017, 1:34 PM
Ah, yes. Because this expect nullable.