Hi all, I'm trying to refactor some code, and I fe...
# announcements
b
Hi all, I'm trying to refactor some code, and I feel like I'm almost there, but I can't find the last missing bit. I have the following code:
Copy code
MemberTbl.select {
    MemberTbl.member_id eq "200"
}.first().also {
   assertThat(it[MemberTbl.id]).isEqualTo("200")
}
But, I'd like to refactor it to something like:
MemberTbl.findByMemberId("200")
with the help of an extension function, since this code is duplicated quite a lot. What I have so far is this:
Copy code
private fun MemberTbl.findByMemberId(s: String, row: ResultRow.() -> Unit) = this.select { member_id eq s }.first().also { row (it)  }
So that my end result will look like this:
Copy code
MemberTbl.findByMemberId("200") {
     assertThat(it[MemberTbl.id]).isEqualTo("200")
}
But that won't, since the
it
in the assertEquals is no longer the closure passed in. How can I fix this?
w
There’s no
assertEquals
in the second snippet. I’m having trouble understanding the issue 🤔
b
@wasyl is this more clear?
w
I think so, yes. So would it work if you had
(ResultRow) -> Unit
instead of
ResultRow.() -> Unit
?
Because with the second one there’s no
it
anymore, instead the value being passed is an implicit receiver, so you can access it with
this
. Perhaps the assertion could look like
this.get(MemberTbl.id).isEqualTo("200"
with current version
b
You're a life saver! 🙂
private fun MemberTbl.findByMemberId(s: String, row:( ResultRow) -> Unit) = this.select { member_id eq s }.first().also(row)
works
Thanks for helping out, appreciate it a lot!! 🌮
👍 1
w
I think these are called function literals with receiver. Basically with
(X) -> Unit
you get
{ it == X }
, while
X.() -> Unit
means
{ this == X}
(and there’s no
it
at all). So you still could use the second one if you wanted to, just with
this
instead of
it
b
That's a great explanation, thanks for that! Getting the braces and brackets in the right spot was the hard part, but with your explanation it makes sense, thanks!