0

This is my code.

fun isJoined(user: User): Boolean {
    val member = requireNotNull(guild.getMember(user)) { return false }
    return joined.contains(member)
}

When member is null, is the funtion 'isJoined' returns false or just anonymous function returns false (so that member to be false)?
If anonymous function returns false, then how can I change my code to return the function 'isJoined'?

nkgcp
  • 147
  • 6

2 Answers2

2

In Kotlin, lambdas with a return automatically default to returning from the innermost function, which means that your entire function will return false. Read here for more info. Also, the elvis operator provides a more elegant way to write this:

val member = guild.getMember(user) ?: return false
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

You can re-write your isJoined() function like this:

fun isJoined(user: User): Boolean =
    guild.getMember(user)?.let { joined.contains(it) } == true

It will do the following things:

  • When guid.GetMember() returns a member, it calls joined.contains(member), which will return a boolean. Comparing a boolean with == true is a noop, so the result of contains(member) is returned.
  • When guild.GetMember() returns null, the let block is not called, and the expression becomes null == true, which returns false.

It's equivalent to this:

fun isJoined(user: User): Boolean {
    val nullableMember = guild.getMember(user)
    return if (nullableMember == null) false else joined.contains(nullableMember)
}
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74