I’ve observed that when a library method accepts a SAM (Single Abstract Method) object as its last argument, I can either call the method using the SAM-constructor syntax or the trailing lambda syntax. (IntelliJ prompts me to use the latter.) Here’s an example using JavaFX:
Yes, if I am writing a Kotlin method that will only be called from Kotlin, that would definitely be my preference. I should give more context to explain why I care about this.
I’m writing a URL-handling library in Kotlin, but it’s intended to be used by any JVM language. Here’s a piece of code from the HostedUri class, allowing the caller to transform the path component of a URL using a function:
/** Set path by running a transform on the parsed path. */
fun mapPath(f: Function<TextPath, TextPath>) = withPath(f.apply(path))
I could have it take a (TextPath) -> TextPath instead, but that would mean exposing the implementation detail of kotlin.jvm.functions.Function1 in the public API, which is less than ideal. Using Function makes the API friendlier to consumers written in Java and other JVM languages.
Hence, my question: Why can’t my Kotlin application that is calling this URL-handling library use trailing lambda syntax for a Function, given that it can use trailing lambda syntax for a Function when calling the Java Stream API?
What is the problem with exposing a type of the kotlin std lib? Your code already exposes the kotlin standard library so it does not create an additional dependency a consumer of your library has to deal with. Just out of interest is Function a custom interface (I can’t find it in the kotlin nor java stdlib)? How is this interface better than the one provided by kotlin? Also what happens if you need a function argument with a different argument count in the future?
While I have my reasons for wanting to use this rather than a kotlin.jvm.functions.Function1, my question is really about why I can’t seem to call my own API with the same syntax as I can call Java APIs, even when I use this existing SAM class.
From a quick read, that only covers cases where someone makes a new interface in Kotlin, right? Function here is a part of the Java stdlib, and I can use trailing lambda syntax with it when calling Java APIs.
You’re right, it’s not KT-7770, it’s https://youtrack.jetbrains.com/issue/KT-11129. The feature “SAM conversion for Kotlin functions” already works in 1.3.61 with the following compiler arguments: