I don't really get this little thingy. I have an abstract class Box
with several sub-classes for different types. For example
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)
Okay, writing unapply makes some trouble. My first idea was to use pattern matching on the type, like this 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 simply doesn't work because of type erasures.
Second attempt was a generic Box[T] with type T and an abstract type member re-defined
in each sub classes. For instance:
abstract class Box[T] {def value : T}
class StringBox(val sValue : String) extends Box[String] {
override def value : String = sValue
}
Consequently, I can re write my unapply 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 doesn't work either. So I guess the explicit type reference
in Box[String] gets erased as well so I need to use a type manifest instead.
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
}
This code compiles (2.10) but still does not the desired implicit conversion.
Why?
Simple question, is there a way to do value extraction without using reflection
or a manifest?
What really boggles me is the question if there is a simple(r) way to combine
polymorphism and pattern matching? If not, are there other ways in Scala to
accomplish a similar effect?
Any idea or suggestions?
Thank you very much.
Prolly you can try this.. :)
abstract class Box[T](val v: T)
object Box {
def apply(s: String) = new StringBox(s)
def apply(b: Boolean) = new BooleanBox(b)
def apply(d: Double) = new DoubleBox(d)
}
class StringBox(sValue: String) extends Box(sValue)
object StringBox {
def unapply(b: StringBox) = Some(b.v)
}
class BooleanBox(sValue: Boolean) extends Box(sValue)
object BooleanBox {
def unapply(b: BooleanBox) = Some(b.v)
}
class DoubleBox(sValue: Double) extends Box(sValue)
object DoubleBox {
def unapply(b: DoubleBox) = Some(b.v)
}
You can use it as --
def useCase[T](box: Box[T]) = box match {
case StringBox("StringBoxxx") => "I found the StringBox!"
case StringBox(s) => "Some other StringBox"
case BooleanBox(b) => {
if (b) "Omg! its true BooleanBox !"
else "its false BooleanBox :("
}
case DoubleBox(x) => {
if (x > 3.14) "DoubleBox greater than pie !"
else if (x == 3.14) "DoubleBox with a pie !"
else "DoubleBox less than a pie !"
}
case _ => "What is it yaa ?"
}
useCase(Box("StringBoxxx")) //> res0: String = I found the StringBox!
useCase(Box("Whatever !")) //> res1: String = Some other StringBox
useCase(Box(true)) //> res2: String = Omg! its true BooleanBox !
useCase(Box(false)) //> res3: String = its false BooleanBox :(
useCase(Box(4)) //> res4: String = DoubleBox greater than pie !
useCase(Box(3.14)) //> res5: String = DoubleBox with a pie !
useCase(Box(2)) //> res6: String = DoubleBox less than a pie !
Related
I'm pretty new to Scala and I'm wondering if it is possible to create a type dynamically in some way. In practice what I want to achieve is something like this:
trait BaseAB
case class A(value: String) extends BaseAB
case class B(value: String) extends BaseAB
def build(name: String, m: String): BaseAB = {
type t = name match {
case "A" => A
base "B" => B
}
new t(m)
}
You can just create new instances in you case clauses, like
case "A" => A(m)
case "B" => B(m)
or you can create partially applied function representing constructor and then provide value
def build(name: String, m: String): BaseAB = {
val construct = name match {
case "A" => A.apply _
case "B" => B.apply _
}
construct(m)
}
> build("A", "boo")
res25: BaseAB = A("boo")
Your code works almost as-is, but it's not because there is some sort of "type-valued runtime-defined variables". Instead, it works because there are companion objects called A and B that have methods apply(s: String): A and apply(s: String): B, and also both conform to type String => BaseAB:
trait BaseAB
case class A(value: String) extends BaseAB
case class B(value: String) extends BaseAB
def build(name: String, m: String): BaseAB = {
val t = name match {
case "A" => A
case "B" => B
}
t(m)
}
In this code snippet, the type of t is inferred to be String => BaseAB (possibly with some additional marker traits like Serializable).
If you are sure that there are only "A" and "B", you can also write it as
(if (name == "A") A else B)(m)
it works for the same reason.
I have a templated class, and depending on the type of T, I want to print something different.
class Clazz[T](fn: T => String) {}
Ideally, I would like to do something like pattern match T (which I can't do):
T match {
case x:Int => println("function from int to string")
case _ => //... and so forth
}
I tried:
class Clazz[T](fn: T => String) {
def resolve():String = fn match {
case f:(Int => String) => println("function from int to string")
case _ => //...etc.
}
}
and the error message I got was that:
non-variable type argument Int in type pattern Int => String is unchecked since it is eliminated by erasure
Is there a way to work around this?
I would use TypeTag so I can compare T to other types without losing any type info:
import scala.reflect.runtime.universe._
class Clazz[T: TypeTag](fn: T => String) {
val resolve = typeOf[T] match {
case t if t =:= typeOf[Int] => "function from Int to String"
case t if t =:= typeOf[Byte] => ..
}
}
But if I just wanted to print out something different from toString, I would go with a type class:
trait Print[T] {
def toText(t: T): String
def apply(t: T) = print(toText(t))
}
def print[T: Print](t: T) = implicitly[Print[T]].apply(t)
implicit object PrintInt extends Print[Int] {
def toText(t: Int) = s"Int: $t"
}
implicit object PrintByte extends Print[Byte] {
def toText(t: Byte) = s"Byte: $t"
}
PrintInt(3) //=> Int: 3
print(3) //=> Int: 3
3.print is even possible if you add this:
implicit class Printable[T:Print](t: T) {
def print = implicitly[Print[T]].apply(t)
}
3.print //=> Int: 3
I thought the following would be the most concise and correct form to collect elements of a collection which satisfy a given type:
def typeOnly[A](seq: Seq[Any])(implicit tag: reflect.ClassTag[A]): Seq[A] =
seq.collect {
case tag(t) => t
}
But this only works for AnyRef types, not primitives:
typeOnly[String](List(1, 2.3, "foo")) // ok. List(foo)
typeOnly[Double](List(1, 2.3, "foo")) // fail. List()
Obviously the direct form works:
List(1, 2.3, "foo") collect { case d: Double => d } // ok. List(2.3)
So there must be a (simple!) way to fix the above method.
It's boxed in the example, right?
scala> typeOnly[java.lang.Double](vs)
res1: Seq[Double] = List(2.3)
Update: The oracle was suitably cryptic: "boxing is supposed to be invisible, plus or minus". I don't know if this case is plus or minus.
My sense is that it's a bug, because otherwise it's all an empty charade.
More Delphic demurring: "I don't know what the given example is expected to do." Notice that it is not specified, expected by whom.
This is a useful exercise in asking who knows about boxedness, and what are the boxes? It's as though the compiler were a magician working hard to conceal a wire which keeps a playing card suspended in midair, even though everyone watching already knows there has to be a wire.
scala> def f[A](s: Seq[Any])(implicit t: ClassTag[A]) = s collect {
| case v if t.runtimeClass.isPrimitive &&
| ScalaRunTime.isAnyVal(v) &&
| v.getClass.getField("TYPE").get(null) == t.runtimeClass =>
| v.asInstanceOf[A]
| case t(x) => x
| }
f: [A](s: Seq[Any])(implicit t: scala.reflect.ClassTag[A])Seq[A]
scala> f[Double](List(1,'a',(),"hi",2.3,4,3.14,(),'b'))
res45: Seq[Double] = List(2.3, 3.14)
ScalaRunTime is not supported API -- the call to isAnyVal is just a match on the types; one could also just check that the "TYPE" field exists or
Try(v.getClass.getField("TYPE").get(null)).map(_ == t.runtimeClass).getOrElse(false)
But to get back to a nice one-liner, you can roll your own ClassTag to handle the specially-cased extractions.
Version for 2.11. This may not be bleeding edge, but it's the recently cauterized edge.
object Test extends App {
implicit class Printable(val s: Any) extends AnyVal {
def print = Console println s.toString
}
import scala.reflect.{ ClassTag, classTag }
import scala.runtime.ScalaRunTime
case class Foo(s: String)
val vs = List(1,'a',(),"hi",2.3,4,Foo("big"),3.14,Foo("small"),(),null,'b',null)
class MyTag[A](val t: ClassTag[A]) extends ClassTag[A] {
override def runtimeClass = t.runtimeClass
/*
override def unapply(x: Any): Option[A] = (
if (t.runtimeClass.isPrimitive && (ScalaRunTime isAnyVal x) &&
x.getClass.getField("TYPE").get(null) == t.runtimeClass)
Some(x.asInstanceOf[A])
else super.unapply(x)
)
*/
override def unapply(x: Any): Option[A] = (
if (t.runtimeClass.isPrimitive) {
val ok = x match {
case _: java.lang.Integer => runtimeClass == java.lang.Integer.TYPE
//case _: java.lang.Double => runtimeClass == java.lang.Double.TYPE
case _: java.lang.Double => t == ClassTag.Double // equivalent
case _: java.lang.Long => runtimeClass == java.lang.Long.TYPE
case _: java.lang.Character => runtimeClass == java.lang.Character.TYPE
case _: java.lang.Float => runtimeClass == java.lang.Float.TYPE
case _: java.lang.Byte => runtimeClass == java.lang.Byte.TYPE
case _: java.lang.Short => runtimeClass == java.lang.Short.TYPE
case _: java.lang.Boolean => runtimeClass == java.lang.Boolean.TYPE
case _: Unit => runtimeClass == java.lang.Void.TYPE
case _ => false // super.unapply(x).isDefined
}
if (ok) Some(x.asInstanceOf[A]) else None
} else if (x == null) { // let them collect nulls, for example
if (t == ClassTag.Null) Some(null.asInstanceOf[A]) else None
} else super.unapply(x)
)
}
implicit def mytag[A](implicit t: ClassTag[A]): MyTag[A] = new MyTag(t)
// the one-liner
def g[A](s: Seq[Any])(implicit t: ClassTag[A]) = s collect { case t(x) => x }
// this version loses the "null extraction", if that's a legitimate concept
//def g[A](s: Seq[Any])(implicit t: ClassTag[A]) = s collect { case x: A => x }
g[Double](vs).print
g[Int](vs).print
g[Unit](vs).print
g[String](vs).print
g[Foo](vs).print
g[Null](vs).print
}
For 2.10.x, an extra line of boilerplate because implicit resolution is -- well, we won't say it's broken, we'll just say it doesn't work.
// simplified version for 2.10.x
object Test extends App {
implicit class Printable(val s: Any) extends AnyVal {
def print = Console println s.toString
}
case class Foo(s: String)
val vs = List(1,'a',(),"hi",2.3,4,Foo("big"),3.14,Foo("small"),(),null,'b',null)
import scala.reflect.{ ClassTag, classTag }
import scala.runtime.ScalaRunTime
// is a ClassTag for implicit use in case x: A
class MyTag[A](val t: ClassTag[A]) extends ClassTag[A] {
override def runtimeClass = t.runtimeClass
override def unapply(x: Any): Option[A] = (
if (t.runtimeClass.isPrimitive && (ScalaRunTime isAnyVal x) &&
(x.getClass getField "TYPE" get null) == t.runtimeClass)
Some(x.asInstanceOf[A])
else t unapply x
)
}
// point of the exercise in implicits is the type pattern.
// there is no need to neutralize the incoming implicit by shadowing.
def g[A](s: Seq[Any])(implicit t: ClassTag[A]) = {
implicit val u = new MyTag(t) // preferred as more specific
s collect { case x: A => x }
}
s"Doubles? ${g[Double](vs)}".print
s"Ints? ${g[Int](vs)}".print
s"Units? ${g[Unit](vs)}".print
s"Strings? ${g[String](vs)}".print
s"Foos? ${g[Foo](vs)}".print
}
Promoting a comment:
#WilfredSpringer Someone heard you. SI-6967
I am trying to cast a String to Int using extractors. My code looks as follows.
object Apply {
def unapply(s: String): Option[Int] = try {
Some(s.toInt)
} catch {
case _: java.lang.Exception => None
}
}
object App {
def toT[T](s: AnyRef): Option[T] = s match {
case v: T => Some(v)
case _ => None
}
def foo(param: String): Int = {
//reads a Map[String,String] m at runtime
toT[Int](m("offset")).getOrElse(0)
}
}
I get a runtime error: java.lang.String cannot be cast to java.lang.Integer. It seems the extractor is not being used at all. What should I do?
Edit: My use case is as follows. I am using play and I want to parse the query string passed in the url. I want to take the query string value (String) and use it as an Int, Double etc. For example,
val offset = getQueryStringAs[Int]("offset").getOrElse(0)
I think the biggest problem here is, that you seem to confuse casting and conversion. You have a Map[String, String] and therefore you can't cast the values to Int. You have to convert them. Luckily Scala adds the toInt method to strings through implicit conversion to StringOps.
This should work for you:
m("offset").toInt
Note that toInt will throw a java.lang.NumberFormatException if the string can not be converted to an integer.
edit:
What you want will afaik only work with typeclasses.
Here is an example:
trait StringConverter[A] {
def convert(x: String): A
}
implicit object StringToInt extends StringConverter[Int] {
def convert(x: String): Int = x.toInt
}
implicit object StringToDouble extends StringConverter[Double] {
def convert(x: String): Double = x.toDouble
}
implicit def string2StringConversion(x: String) = new {
def toT[A](implicit ev: StringConverter[A]) = ev.convert(x)
}
usage:
scala> "0.".toT[Double]
res6: Double = 0.0
There's a problem in your code, for which you should have received compiler warnings:
def toT[T](s: AnyRef): Option[T] = s match {
case v: T => Some(v) // this doesn't work, because T is erased
case _ => None
}
Now... where should Apply have been used? I see it declared, but I don't see it used anywhere.
EDIT
About the warning, look at the discussions around type erasure on Stack Overflow. For example, this answer I wrote on how to get around it -- though it's now deprecated with Scala 2.10.0.
To solve your problem I'd use type classes. For example:
abstract class Converter[T] {
def convert(s: String): T
}
object Converter {
def toConverter[T](converter: String => T): Converter[T] = new Converter[T] {
override def convert(s: String): T = converter(s)
}
implicit val intConverter = toConverter(_.toInt)
implicit val doubleConverter = toConverter(_.toDouble)
}
Then you can rewrite your method like this:
val map = Map("offset" -> "10", "price" -> "9.99")
def getQueryStringAs[T : Converter](key: String): Option[T] = {
val converter = implicitly[Converter[T]]
try {
Some(converter convert map(key))
} catch {
case ex: Exception => None
}
}
In use:
scala> getQueryStringAs[Int]("offset")
res1: Option[Int] = Some(10)
scala> getQueryStringAs[Double]("price")
res2: Option[Double] = Some(9.99)
I have been searching the forum and Google for answers to type erasure issues for Scala. However, I cannot find anything that answers my question.
I struggling with pattern matching on objects that match the type parameter of ParamClass. I need to pattern match on the type of incoming objects to the bar method. I have seen solutions such as
bar[X](a : X)(implicit m : Manifest[X])
which would solve my problem, but I cannot use this as the bar method is an overridden method. (Actually is the receive partial function in the Akka actor framework). The code is given below and should be self explanatory:
class ParamClass[A : Manifest] {
def bar(x : Any) = x match {
case a: A => println("Found A: " + a)
case _ => println("No match: " + x)
}
}
object ErasureIssue {
def main(args: Array[String]) {
val clz = new ParamClass[Int]
clz.bar("faf")
clz.bar(2.3)
clz.bar(12) // this should match, but does not
}
}
ErasureIssue.main(null)
Any help on solving this issue is greatly appreciated. I'm using Scala 2.9.1, BTW.
-J
In theory you could check in bar like this: x.getClass == implicitly[Manifest[A]].erasure, but that fails for primitive types such as Int for which the manifest correctly erases to Int, but bar is called with boxed type java.lang.Integer ... :-(
You could require A to be an AnyRef in order to get the boxed manifest:
class ParamClass[A <: AnyRef : Manifest] {
def bar(x : Any) = x match {
case _ if x.getClass == implicitly[Manifest[A]].erasure =>
println("Found A: " + x.asInstanceOf[A])
case _ => println("No match: " + x)
}
}
object ErasureIssue {
def main(args: Array[String]) {
val clz = new ParamClass[Integer] // not pretty...
clz.bar("faf")
clz.bar(2.3)
clz.bar(12) // ok
}
}
ErasureIssue.main(null)
Given your requirement to construct primitive arrays, you could store directly the boxed class, independently of the unboxed manifest:
object ParamClass {
def apply[A](implicit mf: Manifest[A]) = {
val clazz = mf match {
case Manifest.Int => classOf[java.lang.Integer] // boxed!
case Manifest.Boolean => classOf[java.lang.Boolean]
case _ => mf.erasure
}
new ParamClass[A](clazz)
}
}
class ParamClass[A] private[ParamClass](clazz: Class[_])(implicit mf: Manifest[A]) {
def bar(x : Any) = x match {
case _ if x.getClass == clazz =>
println("Found A: " + x.asInstanceOf[A])
case _ => println("No match: " + x)
}
def newArray(size: Int) = new Array[A](size)
override def toString = "ParamClass[" + mf + "]"
}
val pi = ParamClass[Int]
pi.bar("faf")
pi.bar(12)
pi.newArray(4)
val ps = ParamClass[String]
ps.bar("faf")
ps.bar(12)
ps.newArray(4)
If you try to compile with -unchecked, you immediately get the warning.
test.scala:3: warning: abstract type A in type pattern A is unchecked
since it is eliminated by erasure
case a: A => println("Found A: " + a)
If you now want to go deeper, you can use scalac -print
[[syntax trees at end of cleanup]]// Scala source: test.scala
package <empty> {
class ParamClass extends java.lang.Object with ScalaObject {
def bar(x: java.lang.Object): Unit = {
<synthetic> val temp1: java.lang.Object = x;
if (temp1.$isInstanceOf[java.lang.Object]())
{
scala.this.Predef.println("Found A: ".+(temp1))
}
else
{
scala.this.Predef.println("No match: ".+(x))
}
};
def this(implicit evidence$1: scala.reflect.Manifest): ParamClass = {
ParamClass.super.this();
()
}
};
final object ErasureIssue extends java.lang.Object with ScalaObject {
def main(args: Array[java.lang.String]): Unit = {
val clz: ParamClass = new ParamClass(reflect.this.Manifest.Int());
clz.bar("faf");
clz.bar(scala.Double.box(2.3));
clz.bar(scala.Int.box(12))
};
def this(): object ErasureIssue = {
ErasureIssue.super.this();
()
}
}
}
Now seeing this code you can see that your A has turned into a java.lang.Object, which cause all the parameters to match the clause