How to write asInstanceOfOpt[T] where T <: Any

后端 未结 3 849
借酒劲吻你
借酒劲吻你 2021-02-06 03:41

There\'s a handy implementation of asInstanceOfOpt, a safe version of asInstanceOf, given in the answer to How to write "asInstanceOfOption"

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 03:58

    You could use shapeless's Typeable from Miles Sabin:

    Type casting using type parameter

    It handles primitives and boxing:

    scala> import shapeless._; import syntax.typeable._
    import shapeless._
    import syntax.typeable._
    
    scala> 1.cast[Int]
    res1: Option[Int] = Some(1)
    
    scala> 1.cast[String]
    res2: Option[String] = None
    
    scala> "hello".cast[String]
    res4: Option[String] = Some(hello)
    
    scala> "foo".cast[Int]
    res5: Option[Int] = None
    

    You can see the source here to see how it's written:

    https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/typeable.scala

提交回复
热议问题