https://kotlinlang.org logo
#announcements
Title
# announcements
b

blakelee

04/27/2021, 10:08 PM
I don't think this is possible, but I figured I would ask anyway. Is it possible to chain together multiple enum class into a builder pattern sort of deal For instance I have something like this
Copy code
enum class Page {
    PAGE_1,
    PAGE_2;
}

enum class Page1Section {
    SECTION_A,
    SECTION_B
}

enum class Page2Section {
    SECTION_1,
    SECTION_2
}
With my end goal being something like
Copy code
Page.PAGE_1.SECTION_A.build()
and if I selected PAGE_2 then
Copy code
Page.PAGE_2.SECTION_1.build()
Maybe this would be better in sealed classes If I selected PAGE_1, if I were to type
.
then I would get the list of Page1Section's then if I click
.
again perhaps another list of items
n

Nir

04/27/2021, 10:26 PM
PAGE_1 and PAGE_2 are the same type so I don't off the top of my head see how you could get different completions
but yeah, as you say, sealed classes would work here
1
m

Matteo Mirk

05/12/2021, 2:45 PM
I don’t know about enums but what you’re after looks a lot like the Type-safe Builder pattern to me: https://www.endoflineblog.com/type-safe-builder-pattern-in-java-and-the-jilt-library It allows you to take advantage of the type system to guarantee the correctness of a builder’s usage. But maybe sealed classes would be better suited in this case.
n

Nir

05/12/2021, 3:23 PM
why would you use the builder pattern in kotlin when you have keyword arguments?
m

Matteo Mirk

05/13/2021, 9:33 AM
of course I wouldn’t use it in Kotlin, since we have named and default args, but the OP request looked familiar to what the Type-safe Builder pattern (different from the standard one) can accomplish, so I thought it could be adapted to his use case
4 Views