Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

scala - Type casting using type parameter

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 to some type T. If the conversion fails, the method should return None. I am looking for something similar to this:

def convert[T](key: String): Option[T] = {
  val obj = someJavaMethod(key)
  // return Some(obj) if obj is of type T, otherwise None
}

convert[Int]("keyToSomeInt") // yields Some(1)
convert[String]("keyToSomeInt") // yields None

(How) Can this be achieved using Scala's reflection API? I am well aware that the signature of convert might have to be altered.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...