【发布时间】:2018-05-24 11:15:47
【问题描述】:
我想将字符串转换为scala中的类型。以以下两种情况为例:
case class Product(id: String, title: String, description: String)
type aType = Product
client.getProduct[aType](id, "/products").map { x => println(s"Retrieved Product with id '$id': $x") } // Working
// Retrieved Product with id 'test_id': Some(Product(test_id,MyTitle,The text of my Product))
case class Store(id: String, title: String, Address: String)
type aType = Store
client.getStore[aType](id, "/stores").map { x => println(s"Retrieved Store with id '$id': $x") } // working
// Retrieved Store with id 'test_id': Some(Store(test_id, Store Name,The address of my Store))
我想让这个代码对任何请求都通用,因为已经定义了案例类。例如
case class Product(id: String, title: String, description: String)
case class Store(id: String, title: String, Address: String)
case class API_Detail(Name: String, CaseClassName: String, Api_Url:String)
var API_List = List[API_DS]()
val request_type = "Product" // or "Store"
val id = "test_id"
val API_List_Item = API_List.filter(_.Name == request_type)
// Want to do like this...
type aType = API_List_Item.CaseClassName.toType /**/
val RequestURL = API_List_Item.Api_Url
/* Interested to know how to convert string to type. To my knowledge
some form of reflection will be implemented. */
client.getRespone[aType](id, RequestURL).map { x => println(s"Retrieved $request_type with id '$id': $x") } // Working
// Retrieved Product with id 'test_id': Some(Product(test_id,MyTitle,The text of my Product))
【问题讨论】:
-
这里的产品是案例类。案例类产品(id:字符串,标题:字符串,描述:字符串)
-
我不认为这是可能的,但向我们展示更多的背景,我们也许能够解决它。例如应该如何进一步使用
response?预计谁会调用此代码?您是否希望能够访问response.id(和其他字段)?如果是这样,编译器如何确定(在编译时)response的类型是Product,而您只想在运行时提供实际类型? -
感谢您的回复。我试图详细说明我的要求,但由于 255 个字符的限制而失败。我在以下链接中创建了一个新问题。请看它并帮助我。提前致谢。 stackoverflow.com/questions/47746027/…
-
Waqas,你,作为问题的作者。可以对其进行编辑以提供更多详细信息。您不必在每条有价值的评论之后都创建一个新问题:)。
-
谢谢 SergGr。我已经更新了我的要求。
标签: string scala reflection types