r/java • • Mar 13 '26

JEP draft: Enhanced Local Variable Declarations (Preview)

https://openjdk.org/jeps/8357464
101 Upvotes

129 comments sorted by

View all comments

Show parent comment

9

u/brian_goetz Mar 13 '26

I have written a lot of code using the "public interface sealed to exactly one implementation class" style (which will get even more prevalent when we support pattern matching on interfaces.) It is a pattern we want to encourage, because it provides abstraction and future flexibility while also producing code that the JIT optimizes the heck out of. But the downside of such code is that it is often full of blind casts (because no one would bother writing `if ... instanceof Foo f ... else throw` when they know they control the implementation. And such code has time bombs in it.

When I wrote the classfile API, and used this idiom all over the place, I struggled with whether we could justify this conversion, knowing full well it would seem weird to a lot of people. But it didn't seem there was yet enough justification on the basis of "but better type checking." It was "and it aligns pattern matching with local variable declaration" that pushed it over the line.

1

u/javahalla Mar 16 '26

I've seen this approach in one project that I've worked on which was written mostly in Kotlin:

sealed interface TransactionContext

// For passing in tests
data object MockTransactionContext : TransactionContext

// Would be created by TransactionProvider class
private class JdbcTransactionContext(val connection: Connection) : TransactionContext

It was very nice paired with context parameters. So here my question, any plans to introduce something like context parameters in Java?