I really don't get it. I have an abstract Box class with several subclasses for different types. for instance
abstract class Box
class StringBox(val sValue : String) extends Box
The apply method in the companion object for Box is simple:
object Box{
def apply(s: String) = new StringBox(s)
def apply(b: Boolean) = new BooleanBox(b)
def apply(d: Double) = new DoubleBox(d)
}
so i can write
val sb = Box("StringBox)
Well, writing unapply makes some problems. My first idea was to use pattern matching by type, like this:
def unapply(b: Box) = b match {
case sb: StringBox => Some(sb.sValue)
case bb: BooleanBox => Some(bb.bValue)
case db: DoubleBox => Some(db.dValue)
case _ => None
}
Which just doesn't work due to type erasures.
The second attempt was a common Box [T] with type T, and an element of an abstract type was redefined in each subclass. For instance:
abstract class Box[T] {def value : T}
class StringBox(val sValue : String) extends Box[String] {
override def value : String = sValue
}
Therefore, I can write my non-use as:
def unapply[T](b: Box[T]) = b match {
case sb: Box[String] => Some(sb.value)
case bb: Box[Boolean] => Some(bb.value)
case db: Box[Double] => Some(db.value)
case _ => None
Unfortunately, this does not work either. Therefore, I assume that the explicit type reference in Box [String] is also erased, so I need to use a type manifest. Maybe something like:
def unapply[T](b: Box[_])(implicit target: Manifest[T]): Option[T] = {
if(b.value == target) Some(b.value.asInstanceOf[T])
else None
}
(2.10), .
?
,
?
, , ()
? , Scala
?
?
.