Skip to content

Instantly share code, notes, and snippets.

@leque
Created July 11, 2020 13:51
Show Gist options
  • Save leque/fe7d8c327d2c4a0f39d6aeb30c437407 to your computer and use it in GitHub Desktop.
Save leque/fe7d8c327d2c4a0f39d6aeb30c437407 to your computer and use it in GitHub Desktop.
object Main {
// 型クラスの定義
trait Show[A] {
def show(x: A): String
}
// 型クラスのインスタンス: Int
implicit def ShowInt: Show[Int] = new Show[Int] {
def show(x: Int) = x.toString
}
// 型クラスのインスタンス: Double
implicit def ShowDouble: Show[Double] = new Show[Double] {
def show(x: Double) = x.toString
}
// Showできる何か(型は型パラメータで外に出す)
case class Showable[A](x: A, f: Show[A]) {
def show: String = f.show(x)
}
def showable[A](x: A)(implicit show: Show[A]) = Showable(x, show)
// Showできる何か(型は隠蔽)
trait ShowableRec {
def show: String
}
def showableRec[A](x: A)(implicit f: Show[A]) = new ShowableRec {
def show = f.show(x)
}
def main(args: Array[String]): Unit = {
// 存在型を使ったShowのリスト
val ss : Seq[Showable[_]] = Seq(showable(42), showable(3.14))
println(ss.map(_.show))
// クロージャで中身を隠蔽したShowのリスト
val rs : Seq[ShowableRec] = Seq(showableRec(42), showableRec(3.14))
println(rs.map(_.show))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment