Scala 如何为地图编写 get(name:String, type:Class) [英] Scala How to write a get(name:String, type:Class) for map
问题描述
我希望能够有一个 [String,Any] 类型的地图实现,我可以在其中存储不同类的对象,然后我希望能够做到
I want to be able to have a map implementation of type [String,Any] in which i can store objects of different classes then i want to be able to do
import app.User;
....
usr = map.getAs("user",User)// with usr being an object of Class/Object User. If user is not of that type it throws an exception.
用户之前在地图中的存储位置.
where user was previously stored in the map.
这可能吗?
我什至可以是一个独立的方法,例如
I can even be a standalone method e.g
usr = getAs(map,"user",User)
谢谢
推荐答案
您可以使用 ClassTag
.我对此没有太多经验,但应该可以:
You can use ClassTag
. I don't have a lot of experience with it, but something like that should work:
def getAs[T: ClassTag](m: Map[String, Any], key: String): T =
m(key).asInstanceOf[T]
用法:
val map = Map[String, Any]("one" -> 1, "hello"-> "world")
getAs[String](map, "hello")
res1: String = world
我让您处理异常,您可以简单地将 asInstanceOf
包装在 Try
中,或者您喜欢的任何策略.我还建议将返回类型更改为 Option[T]
.
I let you deal with the exception, you can simply wrap the asInstanceOf
in a Try
, or whichever strategy you prefer. I also recommend changing the return type to Option[T]
.
这篇关于Scala 如何为地图编写 get(name:String, type:Class)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!