我試圖支持框架的ID類型的抽象。例如這裏:Scala中基本類型的可選轉換
object AmINecessary {
case class StringConverter[T](op: String => T)
implicit val toInt = new StringConverter[Int](_.toInt)
implicit val toLong = new StringConverter[Long](_.toLong)
}
class Foo[ID] {
// ID can be String, Long, or Int
import AmINecessary._
// If ID is string, return string, otherwise convert to ID
def getID(id: String)(implicit c: StringConverter[ID] = null): ID = if (c == null) id.asInstanceOf[ID] else c.op(id)
}
這隨後被用作:
val fooString = new Foo[String]
val fooLong = new Foo[Long]
val fooInt = new Foo[Int]
fooString.getID("asdf") // "asdf":String
fooLong.getID("1234") // 1234:Long
fooInt.getID("1234") // 1234:Int
fooInt.getID("asdf") // java.lang.NumberFormatException
可正常工作。我的問題是:
- 使用可選的隱含通過默認爲null,然後分支上感覺壞。什麼是scala方式來實現這一點?
- 真的有必要寫一個字符串的隱式轉換爲long或int嗎?
第二個例子是我在與implicits戰鬥後最終做了什麼。不覺得好,但比隱含的混亂和作品更好。 – rapidninja