Matching patterns on a shapeless type?

All examples I can google for using title casting include a for statement. This works for me, but I was wondering if everything is ok. I'm completely new to formless: this is my first import in 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.

+3


source to share


1 answer


Your approach is fine (although I don't understand how this particular code might work, since it Try

doesn't Future

), but you can actually get a slightly stronger syntax in pattern matching 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 printed as List[Long]

.

+5


source







All Articles