Created
May 31, 2022 14:21
-
-
Save nakamura-to/9451a9340e7e0ba6eb3a47d6d3c0f14c to your computer and use it in GitHub Desktop.
KotlinでScala3のContextual Abstractionsみたいなもの
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 下記の記事の最後のコード例を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