通过模式匹配动态返回案例类的实例

时间:2020-03-03 13:47:27

标签: scala

我有不同的案例类和该案例类的对象,并且我试图实例化该类对象并返回该类。

case class KeySet(KeyID:String,KeyName:String,KeyType:String)
object KeySet{
  def fromXml(node: scala.xml.Node):KeySet = {
    //some operation
    new KeySet(KeyID,KeyName,KeyType)
  }
}

case class NodeSet(NodeID:String,NodeValue:String,NodeType:String,NodeKey:String,NodeLocation:String)
object NodeSet{
  def fromXml(node: scala.xml.Node):NodeSet = {
    //some operation
    new KeySet(NodeID,NodeValue,NodeType,NodeKey,NodeLocation)
  }
}

并且我有一个方法来创建类的实例并返回类对象。

def getConnectionDetails(connectionType:String) : Option[Class[_]]= {
     connectionType match {
       case "KeySet" => Some(() => {
         val xml_cred= scala.xml.XML.loadString("xmlfile")
         KeySet.fromXml(xml_cred)
       })
       case "NodeSet" => Some(() => {
         val xml_cred= scala.xml.XML.loadString("xmlfile")
         NodeSet.fromXml(xml_cred)
       })
       case _ => None
     }
   }

在这里,我在返回类型中遇到错误,每个案例将返回不同的案例类。 此方法的返回类型是什么?

1 个答案:

答案 0 :(得分:2)

在这种情况下,两个案例类之间唯一的共同祖先是AnyRef,因此可以用作函数结果类型的类型。但是,由于类型安全性的丧失,强烈建议不要使用AnyRefAny

相反,您需要点的是通过使用公用Sum Type形成sealed trait,如下所示:

sealed trait ConnectionDetails

case class KeySet(keyID: String, keyName: String, keyType: String) extends ConnectionDetails

case class NodeSet(nodeID: String, nodeValue: String, nodeType: String, nodeKey: String, nodeLocation: String) extends ConnectionDetails


def getConnectionDetails(connectionType:String) : Option[ConnectionDetails]= {
     connectionType match {
       case "KeySet" =>
         val xml_cred= scala.xml.XML.loadString("xmlfile")
         Some(KeySet.fromXml(xml_cred))

       case "NodeSet" => 
         val xml_cred= scala.xml.XML.loadString("xmlfile")
         Some(NodeSet.fromXml(xml_cred))
       case _ => None
     }
   }

因此,您可以在所有其他地方对ConnectionDetails进行模式匹配,这将是安全的。

希望这会有所帮助!