Scala - typesafe“case class”,它有空字段但不使用选项(Scala - typesafe “case class” that has empty fields but doesn't use options)

让我们考虑不断更新背景。 在我的情况下,我有一个很大的功能,我传递了大量的参数,它们在后期阶段初始化并在之后使用。

例如,我不知道在实例初始化时我将从亚马逊获得什么IP,但我知道我将拥有的类型是IP或String ,相同的是堆栈和实例ID。 后来我想使用某种协议连接到这个实例,所以我将使用这个参数。

我可以使用Option s的所有字段构建一个case类,但在我的情况下,这是一个过度杀伤,因为如果我没有成功提升一个实例,我将失败抛出Exception而不是使用一个空选项。 这将导致大量无用的Option.get 。

现在的问题是:我可以使用哪种数据结构,这不是一个Option ,可以轻松复制(=>不可变),我可以在其中声明参数类型,但稍后再初始化它们?

Let's think about continuously updating context. In my case I have quite a big function with tons of parameters that I pass around and they are initialized in later stages and used after that.

For example I don't know what IP I'm going to get from amazon on initialization of an instance, yet I know that the type I'm going to have is IP or String, same about stack and instance ID's. Later I want to connect to this instance using some kind of protocol, so I'll use this parameter.

I could build a case class with all fields that are Options, but in my case it's an overkill, because if I don't succeed raising an instance, I'll fail throwing an Exception instead of using an empty option. This would lead to tons of useless Option.get.

Now the question is: which kind of data structure could I use that's not an Option, can be easily copied (=> immutable) and in which I can declare the types of parameters but initialize them later?

最满意答案

我看到2个选项

使用不可变Map作为系统的配置对象,您可以在那里使用Option支持。 为您的案例类定义空的默认值,这样您就不需要处理选项

I see 2 options

Use immutable Map as a configuration object for your system, you have Options support out of the box there. Define empty default values for your case class, so that you would not need to deal with Options

更多推荐