Skip to content

Instantly share code, notes, and snippets.

@pphilipp
Last active September 25, 2021 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pphilipp/cf61a09c437fdd4616008bd3c49e23d2 to your computer and use it in GitHub Desktop.
Save pphilipp/cf61a09c437fdd4616008bd3c49e23d2 to your computer and use it in GitHub Desktop.
@IntoSet @ElementsIntoSet

MainActivity

val processor = DaggerDecoratorComponent.create().processor()
println("${processor.decorate("Hi how are you?", "noo")}")

DI

@Component(modules = [SetModule::class])
interface DecoratorComponent {
    fun processor(): SetProcessor
}
@Module
object SetModule {
    @Provides
    @JvmStatic
    @IntoSet
    fun provideSparkleDecorator() = Decorator("sparkle") { s -> "✨ $s ✨" }

    @Provides
    @JvmStatic
    @IntoSet
    fun provideEmphasisDecorator() = Decorator("emphasis") { s -> "‼️ $s ‼️" }

    @Provides
    @JvmStatic
    @ElementsIntoSet
    fun provideSetOfDecorators() = setOf(
        Decorator("cool") { s -> "🆒️ $s 😎️" },
        Decorator("noo") { s -> "👎 $s 👎" }
    )

}

Classes

class SetProcessor @Inject constructor(
    private val decorators: Set<Decorator>
) {
    fun decorate(strForDecoration: String, decoratorType: String) = decorators
        .filter { it.displayName == decoratorType }
        .map { it.fn(strForDecoration) }
}
data class Decorator(
    val displayName: String,
    val fn: (String) -> String
)

Output:

[👎 Hi how are you? 👎]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment