Creating unbound service in Kotlin
Asked Answered
A

1

14

I'm trying to create a simple unbound service in kotlin, but I can't. When I override onBind() method in Java I can return null, but in kotlin it says I'm only allowed to return IBinder and not IBinder?, that means it can't be null. Any ideas how to fix that except rewriting MyService class into Java?

[SOLVED] Thank you, guys! I can realy change IBinder to IBinder?. It works!!

Arvy answered 20/7, 2016 at 23:23 Comment(1)
What version of kotlin are you using? Using 1.0.3, when I converted a service the method signature was override fun onBind(intent: Intent): IBinder? and generating the override in Android Studio gave me override fun onBind(intent: Intent?): IBinder but I was able to change that to IBinder? without issueYarbrough
L
20

As Enrico mentioned you can change a type of IBinder to IBinder? and it will be still matching the interface.

An example is below:

override fun onBind(intent: Intent): IBinder? {
   return null
}

In general, be careful when using Android Studio to override Android methods. The real problem comes when it generates non-null type when the system actually can return a null reference. It causes runtime kotlin exceptions you really don't expect.

If I remember correctly I had a lot of issues when overloading Fragment class and methods related to View creation.

Lemke answered 21/7, 2016 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.