Skip to content

Instantly share code, notes, and snippets.

@Biacco42
Created February 21, 2017 04:37
Show Gist options
  • Save Biacco42/86fa4b3e497e760c93cee630afdc5f4a to your computer and use it in GitHub Desktop.
Save Biacco42/86fa4b3e497e760c93cee630afdc5f4a 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() = new Cat("taro")
}
// 既存の型へ適用
implicit object StringCreatable extends Creatable[String] {
def create() = "oooo"
}
def createValue[T]()(implicit Cls: Creatable[T]): T = Cls.create()
// ここの[Cat]が無いとコンパイルできない
// 一方、StringCreatableの定義を消すと、[Cat]がなくてもコンパイルできる
// 返り値からの推論をする前に、Tを不定な状態でClsを探してしまう?
val cat: Cat = createValue[Cat]()
println(cat)
val str: String = createValue[String]()
println(str)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment