https://kotlinlang.org logo
#announcements
Title
# announcements
b

bodiam

10/22/2019, 12:18 AM
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

wasyl

10/22/2019, 12:21 AM
There’s no
assertEquals
in the second snippet. I’m having trouble understanding the issue 🤔
b

bodiam

10/22/2019, 12:23 AM
@wasyl is this more clear?
w

wasyl

10/22/2019, 12:25 AM
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

bodiam

10/22/2019, 12:29 AM
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

wasyl

10/22/2019, 12:33 AM
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

bodiam

10/22/2019, 12:57 AM
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!
2 Views