Last active
December 24, 2015 12:39
-
-
Save potato2003/6799513 to your computer and use it in GitHub Desktop.
implicit def xxx(implicit yyy) が 暗黙的パラメータと理解するために試した。 参考: http://d.hatena.ne.jp/gakuzo/20111204/1323007376
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
class ClassA(val label: String) | |
implicit val arg1:ClassA = new ClassA("ぼくは暗黙的パラメータ") // implicit def foo のための暗黙的パラメータ定義 | |
implicit def foo(implicit a: ClassA):String = { // 引数の implicit 消すと 暗黙的パラメータ見つからないってエラーになる | |
println("fooだよ") | |
a.label | |
} | |
def bar()(implicit argStr:String):String = { | |
println("barだよ") | |
argStr | |
} | |
println(bar()) // bar()はString型の暗黙的パラメータを渡して実行 |
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
fooだよ | |
barだよ | |
ぼくは暗黙的パラメータ |
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
implicit def str2Int(str: String):Int = str.toInt // これは暗黙的変換 | |
implicit val arg1:Int = 1000 // これは暗黙パラメータ | |
implicit def arg2:Long = System.currentTimeMillis // これも暗黙パラメータ。しかしimplicit valとは異なり、毎回評価される | |
implicit def arg3(implicit arg:String):String = System.currentTimeMillis // これも暗黙パラメータ。暗黙パラメータを渡すことができる | |
// 型パラメータとかも受け取れる |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment