是否可以在Scala反射中将字符串转换为类型?

问题描述 投票:0回答:2

我想将字符串转换为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))
string scala reflection types
2个回答
0
投票

谢谢你邀请我参加这个主题。也许您可以通过使用模式匹配来保持解决方案的简单性。使用隐式类的其他解决方案也是有效的。

val requestUrl = "/products"
requestUrl match {
 case "/products" => Products(...)
 case "/store" => Store(...)
 case _ => UnknownType
}

有关模式匹配的其他示例,请参阅allaboutscala.com上的我的教程


0
投票

我正在扩展我之前关于模式匹配的答案。如果我们有Polymorphic Function并且我正在使用Type Classes,则无需重新模式匹配。我还在allaboutscala.com上提供了关于类型类的构建块的详细教程:一般的特征,含义和函数。

您将需要展开getResponse(...)来构建和填充具体类型的字段。

  case class Product(id: String, title: String, description: String)
  case class Store(id: String, title: String, address: String)

  trait Client[T] {
    def getResponse(s: String): Option[T]
  }

  object Client {
    implicit val productClient: Client[Product] = new Client[Product] {
      override def getResponse(s: String): Option[Product] = s match {
        case "/product" => Some(Product("id", "title", "description"))
        case _ => None
     }
  }

   implicit val storeClient: Client[Store] = new Client[Store] {
     override def getResponse(s: String): Option[Store] = s match {
       case "/store" => Some(Store("id", "title", "address"))
       case _ => None
     }
  }

  def apply[T : Client](s: String): Option[T] = 
    implicitly[Client[T]].getResponse(s)
  }

val product: Option[Product] = Client[Product]("/product")
val store: Option[Store] = Client[Store]("/store")
© www.soinside.com 2019 - 2024. All rights reserved.