不時,我處理有東西像它下面的Java:自然斯卡拉 - 約束泛型類型特定類型
def printDbl(d:Double) { println("dbl: " + d) }
def printInt(i:Int) { println("int: " + i) }
,我想在一些斯卡拉包裹這一點,這最終看起來像這樣:
def print[T:Manifest] (t:T) {
if (manifest[T] <:< manifest[Int]) { printInt(t.asInstanceOf[Int]) ; return }
if (manifest[T] <:< manifest[Double]) { printDbl(t.asInstanceOf[Double]) ; return }
throw new UnsupportedOperationException("not implemented: " + manifest[T])
}
,但是當我運行下面,我得到一個運行時異常:
print(1)
print(2.0)
print("hello")
我似乎還記得有一種方法可以在編譯時捕捉到這一點,但我似乎無法將其調出。也許一些巧妙的隱含轉換?
此代碼不好。 – 2012-04-26 08:54:03
我想這個代碼可以通過使用Double/Int而不是String來改進,並且改變代碼的佈局,這樣你就可以做一些事情:隱式地[SpecType [T]]。println(x)例如:http:/ /debasishg.blogspot.de/2010/06/scala-implicits-type-classes-here-i.html – Christian 2012-04-26 09:34:40