Home > Software engineering >  Class constructor asks for 'customPredicate: Message.() -> Boolean' and I cant figure o
Class constructor asks for 'customPredicate: Message.() -> Boolean' and I cant figure o

Time:05-04

I have an the following Interface

interface Filter {
    fun checkFor(message: Message): Boolean = message.predicate()
    fun Message.predicate(): Boolean

infix fun and(otherFilter: Filter): Filter = object : Filter {
    override fun Message.predicate(): Boolean =
        [email protected](this) && otherFilter.checkFor(this)
}

infix fun or(otherFilter: Filter): Filter = object : Filter {
    override fun Message.predicate(): Boolean =
        [email protected](this) || otherFilter.checkFor(this)
}

operator fun not(): Filter = object : Filter {
    override fun Message.predicate(): Boolean = [email protected](this)
}

class Custom(private val customPredicate: Message.() -> Boolean) : Filter {
    override fun Message.predicate(): Boolean = customPredicate()
}

object All : Filter {
    override fun Message.predicate(): Boolean = true
}

In this Interface I have a class named "Custom" which ask in the constructor for

class Custom(private val customPredicate: Message.() -> Boolean)

And I have no idea how should I use this class to create my own Filter

Please assist

CodePudding user response:

There are quite a few ways you can create an object of Custom class.

You can use the lambda expression as a function with the receiver, the receiver is available inside the body as context.

val custom = Custom { //lambda begins here
    //here you can call any method of Message, which is the receiver
}

You can create an extension function of Message and pass its reference to the Custom class constructor.

fun Message.customPredicate() {
    // Your code here
}

Pass reference of this function to the constructor of the Custom class

val custom = Custom(Message::customPredicate)

You can also use an anonymous function for creating an object of the Custom class.

val custom = Custom(fun Message.() {
    // Your code here
})
  • Related