0

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?

jpganz18
  • 5,508
  • 17
  • 66
  • 115
  • Can you explain the use case a bit more? Why do you feel the need to use Lambda with Receiver here? – Todd Jun 06 '19 at 16:24
  • @Todd I basically need to be able to use the receiver with parameter (that I read on the docs) my use case is fictional but Id like for example be able to send as parameter a function from the same data class (in this case "isTheBiggestClub" ) , but such method should be able to receive an external parameter, so I want to send a value. Other example could be I want to send for example the method add(value: Int) to make an addition with an internal value of my data class... – jpganz18 Jun 06 '19 at 16:37

1 Answers1

0

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

r2rek
  • 2,083
  • 13
  • 16