Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on a shapeless type cast ok?

All of the examples I can find with google of the use of Typeable's cast involve a for expression. This is working for me, but I was wondering if this is ok. I'm brand new to shapeless: That's my first import in the lib.

import shapeless.Typeable._

val blarg: Future[Any] = (worker ? ListOfLongsPlx(foo)) // I know Any === Try[List[Long]]
blarg.map {
  _.cast[Try[List[Long]]] match {
    case Some(Success(xs)) => xs
    case Some(Failure(f)) => /* reporting the failure or just default: */ ;  List()
    case None => /*reporting bad cast just a default: */ List()
  }
}

Should I expect problems with this pattern?

To be clear, this is passing my tests.

like image 455
user3928251 Avatar asked Feb 02 '26 14:02

user3928251


1 Answers

Your approach is fine (although I don't understand how that specific code can work since Try isn't Future), but you can actually get a slightly nicer syntax in the pattern match with TypeCase:

import shapeless.TypeCase
import scala.util.{ Failure, Success, Try }

val thing: Any = Try(List(1L, 2L))

val TryListLongCase = TypeCase[Try[List[Long]]]

thing match {
  case TryListLongCase(Success(xs)) => xs
  case TryListLongCase(Failure(f)) => println(f); Nil
  case _ => println("Some unexpected thing"); Nil
}

And the result will be appropriately typed as a List[Long].

like image 96
Travis Brown Avatar answered Feb 05 '26 08:02

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!