Overload by lambda parameter type

Since overloading by lambda parameter count is allowed, I would like to know why overloading by its parameter type is not possible?

fun get(path: String, completionHandler: (response: JSONArray) -> Unit)
fun get(path: String, completionHandler: (response: JSONObject, type: String) -> Unit) // Allowed
fun get(path: String, completionHandler: (response: JSONObject) -> Unit) // Error

Because of Java generics erasure. It is a known problem and there is also a solution for such cases:

@JvmName("handleInts")
fun handle(list: List<Int>) {
	println("handleInts")
}

@JvmName("handleStrings")
fun handle(list: List<String>) {
	println("handleStrings")
}

fun main(args: Array<String>) {
	handle(listOf(1, 2, 3)) // prints: handleInts
	handle(listOf("1", "2", "3")) // prints: handleStrings
}

In your case you would do this:

@JvmName("getJSONArray")
fun get(path: String, completionHandler: (response: JSONArray) -> Unit)
fun get(path: String, completionHandler: (response: JSONObject, type: String) -> Unit) // this one is OK, because it is a diffrent functional type
@JvmName("getJSONObject")
fun get(path: String, completionHandler: (response: JSONObject) -> Unit)
1 Like

Thank you! It works for the function definition but @JvmName annotation is not allowed in the interface it seems.

Unfortunately it seems so:

@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FILE)
@Retention(AnnotationRetention.BINARY)
@MustBeDocumented
public annotation class JvmName(val name: String)