フレームワークの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
:
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)
}
これは次のように使用されています。私の質問は以下のとおりです。
- それは悪いを感じているに分岐し、その後nullにそれをデフォルトによって、オプションの暗黙のを使用して。それを達成するスケーラの方法は何ですか?
- 文字列の暗黙の変換をlongまたはintに記述することは本当に必要ですか?
2番目の例は、私が暗黙のうちに戦った後にやったことです。偉大な気分にはなりませんが、暗黙の混乱や仕事よりも優れています。 – rapidninja