简体   繁体   English

Scala返回未知类型的对象

[英]Scala return object of unknown type

How can I save an object of unknown type in Scala and return it? 如何在Scala中保存未知类型的对象并将其返回?

I have a couple of classes that are all instantiated from the same class like this 我有几个类都是从这样的同一个类实例化的

class And(lhs: ExprTree, rhs: ExprTree) extends ExprTree
class Or(lhs: ExprTree, rhs: ExprTree) extends ExprTree

and a function that needs to return an instance of said classes (ie And(lhs, rhs) but I have no prior knowledge which). 和需要返回所述类的实例的函数(即And(lhs, rhs)但我不知道哪个)。 I also need to store an instance of And() or Or() without prior knowledge which one it is. 我还需要存储And()Or()的实例,而不需要知道它是哪一个。

val expr: ExprTree = ???

will give you an identifier which could take on the value of either an And or an Or . 将为您提供一个标识符,该标识符可以采用AndOr

Similarly, 同样的,

def (...): ExprTree = ???

will give you a function which will return a value of either And or Or (assuming some appropriate parameters, represented here by ...). 将为您提供一个函数,该函数将返回AndOr的值(假设有一些适当的参数,在此以...表示)。

This answer seems far too simple and obvious. 这个答案似乎太简单明了。 But it also seems to satisfy what I think is your request. 但这似乎也满足了我的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM