简体   繁体   中英

how to use a receiver with parameter value in Kotlin?

Ive been trying to do the following:

As an exercise

I need to create a data class with some functions. One method will use a receiver with a parameter to verify if the parameter is bigger than a class value The result will be a boolean.

So far I have this:

data class Club(val name: String, val members: Int) {
fun isABigClub(code: Int.() -> Boolean) : String {
        val isBig = code(this.members)
        return " Your club is a big club? ${isBig}"
    }
}

I created the class club with a name and number of members.

I create a method call isABigClub that only checks if is bigger than certain number I send...

I invoke it in this way

fun main() {
    val isBigClub = club.isABigClub { this > 9 }
    println(isBigClub)

}

Works as expected.

Reading the documentation https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver and other posts What is a purpose of Lambda's with Receiver? What is a "receiver" in Kotlin? find no way to use my receiver while accepting a parameter.

I want to encapsulate the logic of compare inside the data class... something like this

fun isTheBiggestClub(club: Int.(biggestClub: Int) -> Boolean) : Boolean {
        return club(this.members, SOME_RECEIVED_VALUE )
    }

where I actually want to send something similar on my previous example this > 9

Something like club.isTheBiggestClub { this(10) }

I have no idea how to send it or how to read it on the return, find no information about it yet, is it even possible? any idea how?

Your club method returns a Boolean while the isTheBiggestClub method returns String. This might be the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM