[英]Scala: the magic behind implicits
我整個周末都在Scala中玩“隱性游戲”,但是我仍然難以理解整個概念。 這個問題是基於我以前的問題 。 我決定進一步采取以下措施:
def a(b: String)(implicit c: () => String = () => "") = {
println(s"$b - up next is "+c());c();b
}
implicit def conv(s: => String) = () => s
那時候事情開始變得有些古怪:
scala> a("1")(a("2")(a("3")))
3 - up next is
2 - up next is 3
3 - up next is
1 - up next is 2
3 - up next is
2 - up next is 3
3 - up next is
這里的基本思想是使每一行相互引用,如下所示:
1
2 from 1
3 from 2
4 from 3
如果我錯了,請糾正我,但是在這種情況下使用隱式將在發現一個字符串時插入一個字符串。 我不確定為什么要打印7行而不是3行
我在這里做錯了什么? 我開始認為使用隱式會減少我的控制
不是很重要,但是有沒有更安全的隱式方式? 一種讓我確切了解正在發生什么的方式?
您兩次調用c
,而只調用一次:
def a(b: String)(implicit c: () => String = () => "") = {
println(s"$b - up next is " + c())
b
}
然后產生:
3 - up next is
2 - up next is 3
1 - up next is 2
即使首先調用a("1")
,它也必須在產生任何輸出之前調用它傳遞的() => String
。 結果, a("3")
是產生輸出的第一個。
您需要解決這個問題,並讓a("2")
告訴a("3")
從a("2")
調用它:
def a(current: String, next: String => Unit = _ => ())(prev: String) = {
println(s"$current from $prev")
next(current)
}
並像這樣調用它:
a("1", a("2", a("3")))("nothing")
產生:
1 from nothing
2 from 1
3 from 2
要回答您的三點:
() => String
,而不是String
。 -Xlog-implicits
, -Xlog-implicit-conversions
和-Xprint:all
選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.