使用类型参数进行类型转换 [英] Type casting using type parameter

查看:45
本文介绍了使用类型参数进行类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Given 是一个 Java 方法,它返回给定字符串的 java.lang.Objects.我想将此方法包装在 Scala 方法中,该方法将返回的实例转换为某种类型的 T.如果转换失败,该方法应返回None.我正在寻找类似的东西:

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

(如何)这可以使用 Scala 的反射 API 来实现吗?我很清楚 convert 的签名可能需要更改.

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

推荐答案

ClassTag 就是这样:

import reflect.ClassTag

def convert[T : ClassTag](key: String): Option[T] = {
  val ct = implicitly[ClassTag[T]]
  someJavaMethod(key) match {
    case ct(x) => Some(x)
    case _ => None
  }
}

它可以用作提取器,同时测试和转换为正确的类型.

It can be used as an extractor to test and cast to the proper type at the same time.

示例:

scala> def someJavaMethod(s: String): AnyRef = "e"
someJavaMethod: (s: String)AnyRef

[...]

scala> convert[Int]("key")
res4: Option[Int] = None

scala> convert[String]("key")
res5: Option[String] = Some(e)

编辑:但是请注意,ClassTag不会自动取消装箱原语.因此,例如,convert[Int]("a") 永远不会工作,因为 java 方法返回 AnyRef,它必须是 convert[java.lang.Integer]("a"),其他基本类型依此类推.

Edit: note however that a ClassTag does not automatically unbox boxed primitives. So, for example, convert[Int]("a") would never work, because the java method returns AnyRef, it would have to be convert[java.lang.Integer]("a"), and so on for other primitive types.

Miles 对 Typeable 的回答似乎自动处理了这些边缘情况.

Miles's answer with Typeable seems to take care of those edge cases automatically.

这篇关于使用类型参数进行类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆