Hey guys, I’m playing a little bit with simulated ...
# random
d
Hey guys, I’m playing a little bit with simulated intersection types. My use case: I have different classes that share the same pieces of business logic, for example can handle
sorting
,
searching
, etc Those operations share some dependency, for example, a
StateHolder
. An example:
Copy code
class ClassOne(
  private val stateHolder: StateHolderOne
) {
  
  init {
    stateHolder.getSearchQuery()?.let(::search)
    stateHolder.getSorting()?.let(::sort) 
  }
  
  fun search(query: String) {
    stateHolder.setSearchQuery(query)
    ...
  }

  fun sort(sorting: Sorting) {
    stateHolder.setSorting(sorting)
    ...
  }
}

class ClassTwo(
  private val stateHolder: StateHolderTwo
) {
  // may or may not have search, sort, and others
}
What I wanna do, is extract those pieces of logic in reusable components, like
Searchable
,
Sortable
etc, thus each would depend on a (part of)
StateHolder
, e.g.
SearchStateHolder
This is quite easy, but I don’t like easy stuff 🙂 My problem is that I would need to do something like this
Copy code
class ClassOne(
  private val stateHolder: StateHolderOne
) {
  
  val sortable = Sortable(stateHolder, /* other deps */)
  val searchable = Searchable(stateHolder, /* other deps */)
  val other = Other(stateHolder, /* other deps */)
  // etc
}
Indeed, I want to declare a single
Delegate
, that features all the operations I need/are supported by a given
StateHolder
Something like this
Copy code
delegate(
    Searchable,
    Sortable,
    stateHolder = stateHolder // -> StateHolderOne: SearchableStateHolder, SortableStateHolder
) // -> Searchable & Sortable
Well, I got it working, by forcing a bit the compiler https://pl.kotl.in/534LENaCV But I got two problems: • It does work with K2, but with Kotlin 1.9.23 I got this on
stateHolder = stateHolder
Type mismatch: inferred type is Searchable but Sortable was expected
Type mismatch: inferred type is Sortable but Searchable was expected
• I’m fine to force the compiler for where I add this borderline code, but I would gladly avoid suppressing
INCONSISTENT_TYPE_PARAMETER_VALUES
in the client code Got any idea?
For clarity: this part is temporary, just to test the API surface, I will need t change it, otherwise it would completely destroy the purpose of the experiment 😄
Copy code
CombinedDelegate(
    searchable = RealSearchable(stateHolder as SearchableStateHolder),
    sortable = RealSortable(stateHolder as SortableStateHolder)
) as D
In another project I did something like this: 1. https://github.com/fardavide/CineScout/blob/e9a64272b1d32635217d1be15f583603ce68c6[…]lin/cinescout/details/domain/usecase/GetScreenplayWithExtras.kt 2. https://github.com/fardavide/CineScout/blob/e9a64272b1d32635217d1be15f583603ce68c6[…]/commonMain/kotlin/cinescout/details/domain/usecase/GetExtra.kt