Skip to content

Instantly share code, notes, and snippets.

@elizarov
Created June 23, 2022 07:22
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 elizarov/1d92bff4723ea8d7bd138e46e46fc772 to your computer and use it in GitHub Desktop.
Save elizarov/1d92bff4723ea8d7bd138e46e46fc772 to your computer and use it in GitHub Desktop.
List display with contexts
interface Display<in F, in A> {
context(SingleDisplay<A>) fun display(f: F): String
}
interface SingleDisplay<T> {
fun display(f: T): String
}
object IntDisplay : SingleDisplay<Int> {
override fun display(f: Int): String = "Display Int $f"
}
object StringDisplay : SingleDisplay<String> {
override fun display(f: String): String = "Display String $f"
}
class ListDisplay<E> : Display<List<E>, E> {
context(SingleDisplay<E>) override fun display(f: List<E>): String =
f.joinToString(prefix = "Display List [", postfix = "]", separator = ", ") { display(it) }
}
// ----------------------
context(Display<F, A>, SingleDisplay<A>)
fun <F, A> F.display(): String = display(this)
context(SingleDisplay<Int>, SingleDisplay<String>, Display<List<String>, String>)
fun reproducer() {
listOf("hello", "world").display() // OK
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment