David Kubecka
12/12/2023, 2:10 PMtype
Base<out Any>
and not Base<Any>
? How to achieve the latter type?
sealed interface Base<T>
class A : Base<Int>
class B : Base<String>
val cond = false
val type = when (cond) {
true -> A()
false -> B()
}
Sam
12/12/2023, 2:20 PMsealed interface Base<out T>
but that feels like it's just moving the problem ๐David Kubecka
12/12/2023, 2:21 PMSam
12/12/2023, 2:23 PMBase
really is invariant in T
then I think you've answered your own questionDavid Kubecka
12/12/2023, 2:28 PMoverride fun save(messageKey: ..., messageValue: ...) {
val repo = selectRepo(messageKey)
val newDocument = repo.findById(messageKey.id)
?.apply { lastUpdate = messageValue.lastUpdate }
?: messageValue
// this fails because it requires Type in the "in" position
repo.save(newDocument)
}
fun selectRepo(messageKey: ...): Repository<out Type> =
when (...) {
// dispatching here
}
Perhaps there's a different way how to structure this?David Kubecka
12/12/2023, 2:30 PMselectRepo
to directly perform the desired action.Sam
12/12/2023, 2:33 PMoverride fun save(messageKey: ..., messageValue: ...) {
val repo = selectRepo(messageKey)
repo.update(messageKey, messageValue)
}
private fun <T: Type> Repository<T>.update(messageKey, messageValue) {
val newDocument = findById(messageKey.id)
?.apply { lastUpdate = messageValue.lastUpdate }
?: messageValue
// this fails because it requires Type in the "in" position
repo.save(newDocument)
}
Sam
12/12/2023, 2:34 PMupdate
function knows that the type returned by findById
and the type accepted by save
must be the same, even if the actual type is unknownSam
12/12/2023, 2:35 PMDavid Kubecka
12/12/2023, 2:39 PMRepository<out Type>
so findById
also return out Type
and that can't be passed to any method on the repo (because that requires in
).
I will try your suggestion,. Thanks.David Kubecka
12/12/2023, 2:48 PMrepo.update(messageKey, messageValue)
๐Sam
12/12/2023, 2:51 PM?: messageValue
part is messing things up ๐. It should be a solvable problem, but an unchecked cast might be easier ๐David Kubecka
12/12/2023, 2:54 PMmessageValue: CodebookBase
and the error is on messageValue
in repo.update(messageKey, messageValue)
:
Type mismatch.
Required:
CapturedType(out CodebookBase)
Found:
CodebookBase
Sam
12/12/2023, 2:55 PMDavid Kubecka
12/12/2023, 2:56 PMDavid Kubecka
12/12/2023, 3:04 PMrepo
. I guess there really is no clean way around this. I you find some then let me know, though ๐ ThanksDaniel Pitts
12/12/2023, 3:43 PMout
of their common base. Otherwise you could pass in a String to the Int type, or an Int to the String type, or worse yet, a Foo
to the Int type.Daniel Pitts
12/12/2023, 3:43 PM