应用所有这些 Scala 特性在运行时会产生什么样的影响?

发布于 2024-11-18 01:46:27 字数 333 浏览 4 评论 0原文

想象一下:

val myObject = if(someCondition) {
    new Whatever with Trait1
} else if(otherCondition) {
    new Whatever with Trait2 with Trait3 with Trait4
} else {
    new Whatever with Trait5
}

myObject 对象是在运行时“组合”的,还是 scala 编译器足够智能,可以在编译时生成适当的代码?如果您有多个地方应用上述代码中的特征,会对代码产生什么样的性能影响?

Imagine this:

val myObject = if(someCondition) {
    new Whatever with Trait1
} else if(otherCondition) {
    new Whatever with Trait2 with Trait3 with Trait4
} else {
    new Whatever with Trait5
}

Is the myObject object "composed" at runtime, or is the scala compiler smart enough to generate the appropriate code at compile time? What kind of performance impact will it have on the code if you have multiple places that are applying traits like in the above code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

往事风中埋 2024-11-25 01:46:27

它是在编译时组成的。

特征将作为接口添加到结果类型中,并且这些特征中的任何具体方法(通常)将被完整复制到类中。

有时,编译器可能必须通过静态方法的转发器提供具体的实现,但通常情况并非如此。

It's composed at compile-time

The traits will be added as interfaces to the resulting type, and any concrete methods from those traits will (usually) be copied to the class in their entirety.

Occasionally, the compiler may have to provide concrete implementations via forwarders to static methods, but this isn't usually the case.

眼眸里的那抹悲凉 2024-11-25 01:46:27

Scala 将创建三个匿名类(除了最后一个条件是语法错误)。

注意:这些类将使用它们在定义范围内定义的顺序来命名。所以... OuterClass$anon$1 -> 3. 请避免在任何长期 Java 序列化中使用这些匿名类,因为这会锁定代码中匿名类的顺序。

除此之外,这是一个很棒的便利功能!

Scala will create three anonymous classes, (except the last condition is a syntax error).

Note: These classes will be named using the order in which they are defined in the scope they are defined. So... OuterClass$anon$1 -> 3. Please avoid using these anonymous classes in any long-term Java-serialization as this locks down the order of anonymous classes in your code.

Other than that, it's an awesome convenience feature!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文