-
-
Save kmizu/648aea25c92ee56fd8c8fa0eafacc55d to your computer and use it in GitHub Desktop.
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
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