Type casting using type parameter

前端 未结 2 1257
孤独总比滥情好
孤独总比滥情好 2020-12-16 01:46

Given is a Java method that returns java.lang.Objects for a given string. I\'d like to wrap this method in a Scala method that converts the returned instances t

2条回答
  •  不知归路
    2020-12-16 02:07

    You could try shapeless's Typeable,

    scala> import shapeless._ ; import syntax.typeable._
    import shapeless._
    import syntax.typeable._
    
    scala> def someJavaMethod(key: String): AnyRef =
         |   key match {
         |     case "keyToSomeInt" => 23.asInstanceOf[AnyRef]
         |     case "keyToSomeString" => "foo"
         |   }
    someJavaMethod: (key: String)AnyRef
    
    scala> def convert[T: Typeable](key: String): Option[T] =
         |   someJavaMethod(key).cast[T]
    convert: [T](key: String)(implicit evidence$1: shapeless.Typeable[T])Option[T]
    
    scala> convert[Int]("keyToSomeInt")
    res0: Option[Int] = Some(23)
    
    scala> convert[String]("keyToSomeString")
    res1: Option[String] = Some(foo)
    
    scala> convert[String]("keyToSomeInt")
    res2: Option[String] = None
    
    scala> convert[Int]("keyToSomeString")
    res3: Option[Int] = None
    

提交回复
热议问题