2017-06-20 26 views
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更好的語法允許我指定我期望的類型參數。是否有可能在斯卡拉

回答

2

僅次於編譯,但它並沒有真正的工作,我們可以嘗試例如

implicit class Interpolator(val a: StringContext) extends AnyVal { 
    def foo[A](args: Any*): A = args.head.asInstanceOf[A] 
} 

val a = 2 
val second = (new StringContext)foo[String]"a=$a" 
println(second)// this will print a=$a which is not the expected output 

但下面應該工作

implicit class Interpolator[A](val a: StringContext) extends AnyVal { 
    def foo(args: Any*): A = args.head.asInstanceOf[A] 
} 

val a = 2 
val first :Int = foo"a=$a" // : Int is what that does the trick 
println(first) // will print 2 as expected 
+0

這並沒有真正回答這個問題是怎麼在使用字符串插值器語法時提供類型參數。雖然第一個代碼示例的行爲確實很奇怪,但我會承認。 – jedesah

+0

因爲每次運行foo都會創建一個新的Interpolator,所以向Interpolator提供類型參數與將它們提供給foo相同。在我的例子中,它們隱式提供...(通過分配給int val)。所以這是你的問題的答案,如果我失去了一些東西,你能否提供一個代碼示例,以便理解你在做什麼? – oron

+0

我明白了。但是類型論證仍然需要被推斷出來,這就是爲什麼我在問:爲什麼要指定?我希望可以簡單地推斷出我正在處理的情況,因爲這會使事情變得簡單,但不幸的是,情況並非如此。但我現在很好奇爲什麼第二個例子的行爲與第一個例子不同?第一個發生什麼事情來產生意想不到的結果? – jedesah