https://kotlinlang.org logo
#dagger
Title
# dagger
k

kyleg

01/26/2020, 7:13 PM
Can one inject functions using Dagger? I replaced an injectable class that was the command pattern with a function. As a class in the command pattern, the app builds. As the function, I get an error at point of injection
[Dagger/MissingBinding]
Copy code
fun AddUseCase(x: Int): Reader<ReturnValType> = MyReader { ctx -> /* ... */ }
versus
Copy code
class AddUseCase(ctx: MyContext) {
  fun invoke(x: Int): ReturnValType { /* ... */ }
}
w

wasyl

01/26/2020, 7:37 PM
When injecting functions, you need to add
@JvmSuppressWildcards
at injection site:
val injectedStringToStringFunction: (@JvmSuppressWildcards String) -> String
👍 1
t

trevjones

01/30/2020, 3:40 PM
^^ that, but also careful of how many super generic un named functions you have in the graph. My policy is typically to keep unqualified primitives out of the graph to avoid opportunity for ambiguity. the upcoming
fun interface
should help with this usecase quite well.
👍 1
k

kyleg

01/30/2020, 3:41 PM
Yeah in the meantime I just created a data class that holds the functions and inject the data class, but in the long run I don’t want to be injecting 50 use cases into a viewmodel that needs only 1.
2 Views