Last active
July 18, 2023 20:44
-
-
Save marcogrcr/20f4a18980081f832eb8c0712d20f0c3 to your computer and use it in GitHub Desktop.
Ambiguous functional argument overload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.Consumer | |
import java.util.function.Function | |
import java.util.function.Supplier | |
// Take these ambiguous overloads: | |
fun fn(consumerLike: (String) -> Unit) = consumerLike("").also { println("consumer-like") } | |
fun fn(consumer: Consumer<String>) = consumer.accept("").also { println("consumer") } | |
fun <T> fn(functionLike: (String) -> T) = functionLike("").also { println("function-like") } | |
fun <T> fn(function: Function<String, T>) = function.apply("").also { println("function") } | |
fun fn(runnableLike: () -> Unit) = runnableLike().also { println("runnable-like") } | |
fun fn(runnable: Runnable) = runnable.run().also { println("runnable") } | |
fun <T> fn(supplierLike: () -> T) = supplierLike().also{ println("supplier-like") } | |
fun <T> fn(supplier: Supplier<T>) = supplier.get().also{ println("supplier") } | |
// This is how you can invoke them: | |
fun main() { | |
// consumer-like | |
fn { _ -> } | |
// consumer | |
fn(Consumer { }) | |
// function-like | |
fn({ _: String -> 123 } as (String) -> Int) | |
// function | |
fn(Function { _ -> }) | |
// runnable-like | |
fn { -> } | |
// runnable | |
fn(Runnable { }) | |
// supplier-like | |
fn({ -> 123 } as () -> Int) | |
// supplier | |
fn(Supplier { }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment