user20998
user20998

Reputation: 1

it is possible to cast to wrong types without exception in scala

I wrote a code the other day to filter out mixing behavior form a list.

Her is an example code which should describe the problem I ran into.

def myFilter[A](toFilter : Any) : Option[A] = toFilter match {
  case keep : A => Some(keep)
  case _ => None
}

// what happens
myFilter[Int]("hallo") // => Option[Int] = Some(hallo)

// what I expect
myFilter[Int]("hallo") // => Option[Int] = None
myFilter[Int](1) // => Option[Int] = Some(1)

Maybe I'm doing something completely wrong, but it created a lot of problems on my side, I have to create a lot of code now, which I was hoping to make more readable by this function.

Upvotes: 0

Views: 70

Answers (2)

nob
nob

Reputation: 1414

The type went away due Type Erasure. You can however provide the type, try something like

def myFilter[A](toFilter : Any)(implicit classTag: ClassTag[A]) : Option[A] = toFilter match {
  case keep : A => Some(keep)
  case _ => None
}

Upvotes: 1

Ende Neu
Ende Neu

Reputation: 15773

Just provide a ClassTag:

scala> import scala.reflect.ClassTag
import scala.reflect.ClassTag

scala>   def myFilter[A: ClassTag](toFilter : Any) : Option[A] = toFilter match {
     |     case keep : A => Some(keep)
     |     case _ => None
     |   }
myFilter: [A](toFilter: Any)(implicit evidence$1: scala.reflect.ClassTag[A])Option[A]

scala> myFilter[Int]("hallo")
res2: Option[Int] = None

scala> myFilter[String]("hallo")
res3: Option[String] = Some(hallo)

Upvotes: 1

Related Questions