2
implicit class Interpolator(val a: StringContext) extends AnyVal {
def foo[A](args: Any*): A = ???
}
val first = foo[String]"myString" // This does not parse
val second = (new StringContext).foo[String]("myString") // This works but I'm wondering if there is a more concise syntax
val third = foo"myString"[String] // This one is intriguing because it parses but the compiler outputs "method foo does not take type parameters"... what?
絃樂插補指定類型參數如果A
可以推斷那麼這一切都很好,因爲foo"myString"
只會工作,但如果不能,我想知道是否有比second
更好的語法允許我指定我期望的類型參數。是否有可能在斯卡拉
這並沒有真正回答這個問題是怎麼在使用字符串插值器語法時提供類型參數。雖然第一個代碼示例的行爲確實很奇怪,但我會承認。 – jedesah
因爲每次運行foo都會創建一個新的Interpolator,所以向Interpolator提供類型參數與將它們提供給foo相同。在我的例子中,它們隱式提供...(通過分配給int val)。所以這是你的問題的答案,如果我失去了一些東西,你能否提供一個代碼示例,以便理解你在做什麼? – oron
我明白了。但是類型論證仍然需要被推斷出來,這就是爲什麼我在問:爲什麼要指定?我希望可以簡單地推斷出我正在處理的情況,因爲這會使事情變得簡單,但不幸的是,情況並非如此。但我現在很好奇爲什麼第二個例子的行爲與第一個例子不同?第一個發生什麼事情來產生意想不到的結果? – jedesah