I just started playing with context receivers (in ...
# language-evolution
m
I just started playing with context receivers (in database context) and had a use-case for optional context receiver with default, basically to express “if I already have a transaction open (= in context) use it, else create a new transaction”. I don’t think that would be possible right now. I would think something like this should be possible (using Jackson ObjectMapper as an example)
Copy code
context(ObjectMapper?) fun valueToJsonString(obj: Any): String {
    return (this@ObjectMapper ?: defaultObjectMapper()).writeValueAsString(obj)
}
Actually, it seems like its not even possible to use nullable receivers this way, IntelliJ does not recognize the
this@ObjectMapper
if the context parameter is nullable.
👍 1
y
In this case, you can define the main bulk of your function with a context receiver, and then provide a context-less overload that runs a transaction. Btw, how do you expect to close that newly-created transaction? If you have a default value of a new transaction, you need some way to know to close it at the end of the function. With the overload approach that's possible right now, you get to end the transaction afterwards
m
To explain the situation a bit further, my use case was a class hierarchy of different localization approaches with generic “toString”-like methods that depending on the sub-class use different approaches to actually return a string in a given locale. One sub-class uses a database table to retrieve localizations, and only in this subclass do I even need transactions, for a simple read on the DB. With Exposed, I don’t really need to manually close the transaction, because at one point the TA scope will be left and then it closes, so that would not be a problem in that specific case. Also as you can imagine, this localization code is called all over the place and sometimes, I may already be inside a transaction, sometimes not. But its actually not a problem after all in my specific context, I added the class allowing me to open a new transaction on my database as context and just create the transaction inside the method (First I thought that would lead to problems, which wasn’t the case) But thank you for explaining the overload approach, I’m sure I will need that soon enough 👍