Created
February 21, 2017 04:37
-
-
Save Biacco42/86fa4b3e497e760c93cee630afdc5f4a to your computer and use it in GitHub Desktop.
This file contains hidden or 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() = 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