How to write following code in Kotlin for callback implementation
Asked Answered
U

2

7

how do i write in Kotlin like java?


Callback callback= new Callback()
 {
     @Override
     public void getCallback(ServerResponse serverResponse) {

     }
 }
Uncurl answered 29/6, 2017 at 8:55 Comment(0)
G
9

You can use following code in Kotlin.

var callback:Callback = object:Callback() {
  fun getCallback(serverResponse:ServerResponse) {
  }
}

You can use this link to convert your Java code to kotlin. https://try.kotlinlang.org

Geostatics answered 29/6, 2017 at 9:3 Comment(1)
var callback:CallBack = object:CallBack { override fun callBackFun(obj: Any, function: () -> Unit) { } }Uncurl
D
12
var callback:Callback = object:Callback() {
  override fun getCallback(serverResponse:ServerResponse) {
  }
}

var callback:Callback says that the variable type is a Callback

object:Callback() { } is an anonymous class. It has no name when created, before being assigned to var callback. It's similar to the new Callback() code.

override replaces @Override

fun indicates that it is a function

Dietitian answered 30/7, 2017 at 3:19 Comment(1)
I think it's not an anonymous function, rather it's an anonymous class, which implements the Callback interface. Actually the overridden function getCallback has a name, 'getCallback', which is not anonymous.Bwana
G
9

You can use following code in Kotlin.

var callback:Callback = object:Callback() {
  fun getCallback(serverResponse:ServerResponse) {
  }
}

You can use this link to convert your Java code to kotlin. https://try.kotlinlang.org

Geostatics answered 29/6, 2017 at 9:3 Comment(1)
var callback:CallBack = object:CallBack { override fun callBackFun(obj: Any, function: () -> Unit) { } }Uncurl

© 2022 - 2024 — McMap. All rights reserved.