Say I declare a `fun interface Foo` and I have `cl...
# getting-started
d
Say I declare a
fun interface Foo
and I have
class Bar(val foo: Foo)
I can still create
Bar
using a lambda that doesn't implement the fun interface... but when I try to do
fun provideFoo(): Foo = { ... }
, it doesn't let me... why not? What's the difference? Can I maybe cast it to work somehow without wrapping it in a
Foo { { }() }
?
s
e
using a lambda that doesn't implement the fun interface
that's not true, the lambda in that context does implement the fun interface. if you write
Copy code
val foo: (...) -> ... = { ... }
there is no automatic conversation that lets you write
Copy code
Bar(foo)
only trailing lambdas get SAM converted without specifying the interface type
d
It seems like this works:
Copy code
val someLambda = { ... }

fun provideFoo(): Foo = Foo(someLambda)
I wonder if that syntax is documented somewhere...
e
e.g.
Copy code
Bar { ... }
is really
Copy code
Bar(Foo { ... })
yes, that was added sometime around 1.6
you end up with an extra wrapper lambda object that way though
d
😕
At least I don't have to rewrite all the params and pass them down to the other lambda... it's not even really a lambda but rather a function reference.
d
My fun interface represents a use case, and I'm just calling the repository's function that implements it instead of giving it access to the repo... but it doesn't make sense for the repo to implement the use case, since it's in a different layer.
I saw that example but I don't understand what
::Printer
does... you're calling a function reference on the actual
fun interface
...?
What's the declaration of that
addPrinter
method?
j
I think this is working in K2
d
I still don't understand what
::Printer
is instantiating, it's just an interface w/o an implementation?
e
it is referencing the
Copy code
(() -> Unit) -> Printer
"constructor" which you used to need to write by hand but is now provided by the Kotlin compiler