Skip to content

Instantly share code, notes, and snippets.

@Pooh3Mobi
Created July 11, 2018 14:59
Show Gist options
  • Save Pooh3Mobi/eb8d9aef28174ee8eda466d9564b12c2 to your computer and use it in GitHub Desktop.
Save Pooh3Mobi/eb8d9aef28174ee8eda466d9564b12c2 to your computer and use it in GitHub Desktop.
differential programming at kotlin
interface AFunctionExecutor {
fun execute(tag: String = "None", name: String = "Taro", age: Int=32)
}
class DefaultFunctionExecutor : AFunctionExecutor {
override fun execute(tag: String , name: String, age: Int) = println("[$tag] $name($age)")
}
class SoccerFunctionExecutor : AFunctionExecutor {
override fun execute(tag: String, name: String, age: Int) {
println("[SOCCER] $name($age)")
}
}
class VolleyBallFunctionExecutor : AFunctionExecutor {
override fun execute(tag: String, name: String, age: Int) {
println("[VOLLEYBALL] $name($age)")
}
}
fun main(args: Array<String>) {
val choseExecutorBy = fun(subject: Subject) = when(subject) {
Subject.SOCCER -> SoccerFunctionExecutor()
Subject.VOLLEY -> VolleyBallFunctionExecutor()
Subject.DEFAULT -> DefaultFunctionExecutor()
}
val executor = choseExecutorBy(Subject.SOCCER)
executor.execute(name = "Neko", age = 3) // [SOCCER] Neko(3)
}
enum class Subject {
SOCCER, VOLLEY, DEFAULT
}
interface AFunctionExecutor {
fun execute(tag: String = "None", name: String = "Taro", age: Int=32)
}
class DefaultFunctionExecutor(private val tagProvider: (() -> String)? = null) : AFunctionExecutor {
override fun execute(tag: String, name: String, age: Int) =
println("[${ tagProvider?.let { tagProvider.invoke() } ?: tag }] $name($age)")
}
class DelegationExecutor(private val default: DefaultFunctionExecutor): AFunctionExecutor by default
fun main(args: Array<String>) {
val choseExecutorBy = fun(subject: Subject) = when(subject) {
Subject.SOCCER -> DelegationExecutor(DefaultFunctionExecutor { "SOCCER" })
Subject.VOLLEY -> DelegationExecutor(DefaultFunctionExecutor { "VOLLEY" })
Subject.DEFAULT -> DelegationExecutor(DefaultFunctionExecutor())
}
val executor = choseExecutorBy(Subject.SOCCER)
executor.execute(name = "Neko", age = 3) // [SOCCER] Neko(3)
}
enum class Subject {
SOCCER, VOLLEY, DEFAULT
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment