https://kotlinlang.org logo
#exposed
Title
# exposed
j

JP

11/13/2020, 4:13 AM
What's the best way to wait to execute a
transaction
? I want to take one in as a parameter in a function, and then execute the transaction. However, I've only ever seen it in the inline style of
transaction {...}
and having it execute there
j

Joel

11/13/2020, 1:08 PM
Copy code
fun Transaction.doSomething() {
  ...
}

transaction {
  doSomething() // this is Transaction
}
You could technically pass the
Transaction
as an argument but I have not seen any code like that.
j

JP

11/14/2020, 3:01 PM
Thank you @Joel! What if I want to have it as part of an interface? I have
Copy code
interface Foo {
    val doSomething: Transaction.() -> Unit
}
but when I try calling the transaction function, it doesn't like it
Copy code
fun(f: Foo){
    transaction{
        f.doSomething() // Errors here
    }    
}
How come I can't do that, or is there a better way to do it? I essentially just want the interface to have a transaction, but not have it be executed until later
j

Joel

11/14/2020, 3:05 PM
What is the error? I would write
fun Transaction.doSomething()
instead of assigning a
val
. Unsure if this is causing an issue.
but not have it be executed until later
You don't want transactions to be kept open for a while. This can cause inconsistencies in the database, tie up valuable pooled resources, etc. Exposed's transaction block model helps nudge you in the direction of concise statements.
What you might mean is that the interface requires an existing transaction, in which case the extension function is definitely the right approach.
j

JP

11/14/2020, 3:44 PM
🤦‍♂️ it would help if I had the right member type, that would certainly do it. That looks like the approach I want to take, thank you! I think I'll use
Copy code
interface Foo {
    fun doSomething: Transaction.() -> Unit
    fun execute() {
        transaction {
            doSomething()
        }
    }
}
j

Joel

11/14/2020, 3:47 PM
Copy code
interface Foo {
  fun Transaction.doSomething()
}

fun Foo.execute() = transaction { doSomething() }
5 Views