开发者

What kind of impact does applying all these Scala traits have at runtime?

开发者 https://www.devze.com 2023-03-16 18:18 出处:网络
Imagine this: val myObject = if(someCondition) { new Whatever with Trait1 } else if(otherCondition) { new Whatever with Trait2 with Trait3 with Trait4

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?


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.


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号