I am trying to get SAM conversion working. Why do ...
# announcements
s
I am trying to get SAM conversion working. Why do I get errors right side of assignment in both
foo2
,
foo3
?
Copy code
interface Foo {
    fun bar()
}

private val foo: Foo = object : Foo {
    override fun bar() {
        TODO("Not yet implemented")
    }
}

private val foo2: Foo = {}
private val foo3: Foo = Foo {}
j
fun interface ...{ ... }
s
Yup; but that will only fix the
foo3
assignment The
foo2
assignment is invalid.
s
Ah silly me. Thanks. Any idea why the fun interface is mandatory rather than optional like in Java?
Seems to really spoil the fun of it
n
I think just for the obvious reason of allowing the person writing the interface to opt in
I think it makes more sense; the thing is in Java you have tons of existing code that's awkward because Java didn't have lambdas in the past
So by making it automatic in Java, you're able to improve the usage of all this older code without that coding needing to be updated
That's a big consideration. In Kotlin, it's common to just use callables to begin with. A lot of people seem to view the major incentive behind
fun interface
anyhow as writing code in Kotlin that's nice to call from both Java and Kotlin.
s
I dont find it obvious at all. Seems there isnt a KEEP for it either.
n
Sorry what part is not obvious?
s
Why the author must allow users of an interface to be able to use SAM conversion.. which just keeps the situation that kotlin interfaces are inferior (albeit a bit less) java interfaces even in a Kotlin codebase
r
The rules are the same as in Java as far as I'm aware. You can't do
val x: Runnable = {}
You can only use the shortest version in higher order functions, and that works for both Kotlin and Java.
Copy code
fun test1(foo: Foo) { ... }
fun test2(x: Runnable) { ... }

test1 { ... }  // Works
test2 { ... }  // Also works
n
I have to say, I really don't love that behavior.
you would sort of expect that binding to variables and binding to arguments is the same; this is either 100% or 99% true in most languages I've used.
The whole feature is a bit awkward in the context of Kotlin, because no matter how you slice it, it's essentially implicit conversion
r
I find it rather unintuitive as well. I was only trying to clear up the misconception that Java and Kotlin are treated differently in this regard.
n
Makes sense.
I guess if the compile time interfaces thing had landed, there would have been a better solution; people who wanted this behavior could have basically made it so that appropriate function signatures implement their interface
and it wouldn't have been such a one off