https://kotlinlang.org logo
Title
m

marcinmoskala

04/29/2021, 5:42 AM
When do you use fun interface instead of function type?
d

dave08

04/29/2021, 9:26 AM
function type? You mean lambdas?
m

marcinmoskala

04/29/2021, 10:35 AM
Lambdas can be used with both function type and function interface.
// fun type
val a: ()->Unit = { print("A") }

// fun interface
fun interface A {
   fun call()
}
val a: A = A { print("A") }
d

dave08

04/29/2021, 10:55 AM
I personally prefer
fun interface
when it needs to be passed in for a specific purpose (like a specific type of event. Even though when implementing them the lambda looks the same more or less, but there's some restrictions as to where they can be passed. But recently I wanted to use it to implement a base UseCase interface, in the production code, I would implement it as a full class with deps on repos and such, whereas in my test code, I can provide a one-liner to Stub them. (The problem is that they don't work with
suspend fun
yet, so I had to try something else for that...)
Regular lambdas I use inside classes (not passed as dependencies to be implemented for a specific purpose), their name is usually enough to clarify their purpose, and multiple implementations for the same purpose are less common there...
o

Orhan Tozan

04/29/2021, 5:18 PM
@dave08 try this, this is the pattern I'm using for Usecases:
interface MyUseCase {
    suspend operator fun invoke(foo: Foo): Bar
}

...

val myUseCase: MyUseCase = ...
val bar = myUseCase(foo)
d

dave08

04/29/2021, 8:12 PM
Yup, that's currently what I use, but for stubs to be one liners in our tests, I had to make a UseCase inline fun taking a lambda... instead of a simpler fun interface...
I made the interface with generics though, and the DI distinguishes use cases by their command object type (the Foo in your example)