Skip to content

Instantly share code, notes, and snippets.

@kmizu
Forked from Biacco42/StaticTypeInfer.scala
Last active February 21, 2017 05:02
Show Gist options
  • Save kmizu/648aea25c92ee56fd8c8fa0eafacc55d to your computer and use it in GitHub Desktop.
Save kmizu/648aea25c92ee56fd8c8fa0eafacc55d to your computer and use it in GitHub Desktop.
object Main extends App{
trait Creatable[T] {
def create(): T
}
class Cat(val name: String)
// 自作の型への適用
implicit object Cat extends Creatable[Cat] {
def create(): Cat = new Cat("taro")
}
// 既存の型へ適用
implicit object StringCreatable extends Creatable[String] {
def create(): String = "oooo"
}
def createValue[T]()(implicit Cls: Creatable[T]): T = Cls.create()
// ここの[Cat]が無いとコンパイルできない
// 一方、StringCreatableの定義を消すと、[Cat]がなくてもコンパイルできる
// 返り値からの推論をする前に、Tを不定な状態でClsを探してしまう?
val cat = createValue[Cat]()
println(cat)
val str = createValue[String]()
println(str)
def readCat(cat: Cat): Any = cat
readCat(createValue())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment