Last active
September 12, 2020 17:18
-
-
Save emanon-was/81bdd00012f747cfd70f399103132996 to your computer and use it in GitHub Desktop.
RustのFromトレイトを模倣したかったが…
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
interface Static<T> | |
data class Target(val a: Int) { | |
companion object : Static<Target> | |
} | |
interface From<T, U> { | |
fun Static<T>.from(value: U) : T | |
} | |
interface FromInt<T> : From<T, Int> { | |
override fun Static<T>.from(value: Int) : T | |
} | |
interface FromStr<T> : From<T, String> { | |
override fun Static<T>.from(value: String): T | |
} | |
object TargetFromInt : FromInt<Target> { | |
override fun Static<Target>.from(value: Int) : Target = Target(value) | |
} | |
object TargetFromStr : FromStr<Target> { | |
override fun Static<Target>.from(value: String) : Target = Target(value.toInt()) | |
} | |
fun main() { | |
val kotlin = | |
TargetFromStr.run { | |
TargetFromInt.run { | |
Target.from(2) | |
Target.from("10") | |
} | |
} | |
println(kotlin) | |
} |
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
trait FromFor[B] { | |
def from[A](a: A)(implicit ctx: From[A]): B = ctx.from(a) | |
trait From[A] { | |
def from(a: A): B | |
} | |
} | |
trait Into[A] { | |
val self: A | |
def into[B](implicit ctx: FromFor[B]#From[A]): B = ctx.from(self) | |
} | |
implicit class IntoFor[T](val self: T) extends Into[T] | |
class Target(val x: Int) | |
object Target extends FromFor[Target] { | |
implicit object FromInt extends From[Int] { | |
def from(a: Int) = new Target(a) | |
} | |
implicit object FromStr extends From[String] { | |
def from(a: String) = new Target(a.toInt) | |
} | |
} | |
Target.from(10) | |
Target.from("20") | |
30.into[Target] | |
"40".into[Target] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment