So sealed interfaces are coming (<https://blog.jet...
# announcements
s
So sealed interfaces are coming (https://blog.jetbrains.com/kotlin/2021/02/new-language-features-preview-in-kotlin-1-4-30/#sealed-interfaces) with
Copy code
Kotlin 1.5 removes both constraints: you can now make an interface sealed. The subclasses (both to sealed classes and sealed interfaces) should be located in the same compilation unit and in the same package as the super class, but they can now be located in different files.
Now my question is, can you still extend a sealed interface in a TestCase (within the same module)? Do the tests within a Gradle
test
-folder belong to the same sourceSet (and therefore compilation unit?) as the sources under
src
?
s
Seems like great feedback you should submit to JB
e
Do you have example why would you need a test implementation of the sealed class?
m
That doesn't make sense and likely won't work.
when
expressions in the main source set would no longer be exhaustive because they don't know about tests.
2
s
I'm thinking more about sealed interfaces (not sealed classes) that I want to mock. The website names as a use case (for sealed interfaces) a lib with an interface they don't want their customers to implement, that doesn't mean they (the developers of the lib) don't want to mock that interface in one of their unit tests.
m
But what would
when
statements do if they encounter an unexpected implementation? That defeats the purpose of
sealed
. Instead, you should mock each
interface
that extends your
sealed interface
.
s
sealed interfaces aren't all about the when statements, but also about interfaces you don't want your users to extend.
m
Otherwise the definition says “only
A
and
B
implement `S`” but the test says “okay, here’s unrelated `C`“. How would your library be able to handle that?
Copy code
when (s) {
  is A ->
  is B ->
} // crash?
They can be used for that but you cannot break the contract of
sealed
in Kotlin. You may be able to do so with Java or maybe by suppressing the error in Kotlin. But both would be a hack.
Also it’s not just
when
. It also affects casting, smart casts and probably other functionality.