Use typealias vs interface for action listener

Use typealias

// bad
interface CallBackListener {
   fun onHoge(foo: String, bar: Int)
}

// caller
var callback: CallBackListener? = null
callback?.onHoge("foo", 100)

// callee
val callback = object : CallBackListener {
  override fun onHoge(foo: String, bar: Int) {
    print("$foo : $bar")
  }
}

// good
typealias CallBackListener = (foo: String, bar: Int) -> Unit

// caller
var callback: CallBackListener? = null
callback?.invoke("foo", 100)

// callee
val callback = { foo, bar -> 
  print("$foo : $bar")
}

typealias vs interface, which is the best choose ?

I do not know about other forum users, but I have a policy of not reading a code untill it is formatted like the code. Markdown supports it via “```kotlin” environment.

As for the question. Why do you need typealias at all? Why not use type (String, Int) -> Unit?

If you want good compatibility for calling from Java you’d want the interface. Possibly with an invoke operator that makes invocation work as normal. You would probably want to use Java for the interface as that allows Kotlin to use lambda’s with it.