Compiler is unable to pick between two methods with function arguments

fun sample(function: () -> Set<Any>) {}
fun sample(function: () -> Any) {}

fun main(args: Array<String>) {
	sample { setOf() }
	sample { "" }

Why does the sample { "" } error (type mismatch, expected Set)? Shouldn’t it be able to resolve to the method? I know that Java interop might break this, but I thought the JvmName trick got around that.


This is the way how overload resolution works in Kotlin. First it selects the most specific overload, then it infers types and analyzes types inside the lambda body. It means that the body of lambda currently doesn’t affect the overload resolution process.

There’s a general feature request for that KT-11265, though it is slightly different, because there none of overloads can be chosen. Your case is closer to KT-23883.