Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created May 31, 2022 14:21
Show Gist options
  • Save nakamura-to/9451a9340e7e0ba6eb3a47d6d3c0f14c to your computer and use it in GitHub Desktop.
Save nakamura-to/9451a9340e7e0ba6eb3a47d6d3c0f14c to your computer and use it in GitHub Desktop.
KotlinでScala3のContextual Abstractionsみたいなもの
// 下記の記事の最後のコード例をKotlinで書いてみた
// https://zenn.dev/hinastory/articles/c8d5267ea43ed6
package hello.kotlin
data class Person(val name: String, val age: Int)
data class Japanese(val name: String, val age: Int, val info: String)
interface CanGreet<T> {
fun T.hello()
}
object PersonCanGreet: CanGreet<Person> {
override fun Person.hello() = println("hello!")
}
object JapaneseCanGreet: CanGreet<Japanese> {
override fun Japanese.hello() = println("こんにちは。実はわたしは、${info}なんです。")
}
context(CanGreet<T>)
fun <T> greeting(a: T) = a.hello()
fun main() {
val alexa = Person("Alexa", 12)
val hanako = Japanese("Hanako", 18, "テニスが趣味")
with(PersonCanGreet) {
with(JapaneseCanGreet) {
greeting(alexa)
greeting(hanako)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment