4

How do I do something like this in Scala?

case class Foo[A](x: A) {

  def get[T]: Option[T] = x match {
    case x: T => Some(x)    // if x is of type T i.e. T =:= A
    case _ => None
  }
}

val test = Foo("hi")
assert(test.get[Int] == None)
assert(test.get[String] == Some("hi"))

I tried this and ran into some weird time inference failure:

import scala.util.{Try, Success}
import reflect._

case class Foo[A](x: A) extends Dynamic {

  def get[T: ClassTag]: Option[T] = Try(x.asInstanceOf[T]) match {
    case Success(r) => Some(r) 
    case _ => None
  }
}

object Foo extends App {
  val test = Foo("hi")
  val wtf: Option[Int] = test.get[Int]
  assert(wtf.isInstanceOf[Option[String]])
  assert(wtf == Some("hi"))     // how????
  // val wtf2: Option[String] = wtf  // does not compile even if above assert passes!!
}
pathikrit
  • 29,060
  • 33
  • 127
  • 206
  • Look at the warning when you compile this with the `-unchecked` flag: `scala> case class Foo[A](x: A) { | | def get[T]: Option[T] = x match { | case x: T => Some(x) // if x is of type T i.e. T =:= A | case _ => None | } | } :10: warning: abstract type T in type pattern T is unchecked since it is eliminated by erasure case x: T => Some(x) // if x is of type T i.e. T =:= A`. Then see http://stackoverflow.com/a/3789230/2197460. Not an answer, but a start. – Dave Swartz Mar 12 '14 at 03:23
  • The link you posted has the author asking about the generic `T` case at the end of the question – pathikrit Mar 12 '14 at 03:46
  • s/time/type. Or, s/work/sleep. – som-snytt Mar 12 '14 at 06:23

2 Answers2

2

Surely a dupe, but hastily:

scala> :pa
// Entering paste mode (ctrl-D to finish)

import reflect._
case class Foo[A](x: A) {

  def get[T: ClassTag]: Option[T] = x match {
    case x: T => Some(x)    // if x is of type T i.e. T =:= A
    case _ => None
  }
}

// Exiting paste mode, now interpreting.

import reflect._
defined class Foo

scala> val test = Foo("hi")
test: Foo[String] = Foo(hi)

scala> test.get[Int]
res0: Option[Int] = None

scala> test.get[String]
res1: Option[String] = Some(hi)
som-snytt
  • 38,672
  • 2
  • 41
  • 120
0

If you can throw out the get:

case class Foo[A](x: A)
Seq(Foo("hi"), Foo(1), Foo(2d)).collect { case f @ Foo(x: String) => f }.foreach(println)

results in:

Foo(hi)

And the others are similarly trivial.

Dave Swartz
  • 890
  • 6
  • 14
  • The `get` was just a simplification for StackOverflow - I do need a method with generic type `T` in it. – pathikrit Mar 12 '14 at 03:47