@NeverBox inline class

Instead of silently emitting boxing code, trigger compiler error on uses that would incur boxing.

  • Usually, this is what I want. Right now, You have to check manually, which is very error prone. I believe this is how most inline classes will be intended to be used.

Solves most conceptual problems, that I know of, with inline classes. (e.g:)

  • Private constructor / init blocks / checking.
  • Weird edge cases related to auto boxing: all is an error.
  • Can implement interface, without worrying about using it with a normal fun. (~only inline fun will work)
  • No need to worry about performance overhead of accidental boxing: Compiler checks for you it never happens.

(In my opinion, this should have been the default, with @AutoBox (current behavior) as opt-in, but Iā€™m afraid that cannot change anymore)

While ~easy to write yourself, a variant of @NeverBox could be @ManualBox which would turn

@ManualBox
inline class A(val data: Int) : CharSequence {
    //...
}

into

@NeverBox
inline class A(val data: Int) : CharSequence {
    //...
    inline fun box() = Box(this)
    class Box(val unbox: A) : CharSequence //automatically share impl of interfaces
}

.

8 Likes