Oh,yeah.I simplified a bit of code.
fun paidMore(amount: Int, employee: Employee,
predicate: (Int, Employee) -> Boolean = { _, _ -> employee.salary > amount }
): Boolean = predicate(amount, employee)
now,I simplified the code again
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertFalse
import kotlin.test.assertTrue
object ClosureSpec : Spek({
describe("Test, add a default implementation to the function") {
data class Employee(val name: String, val salary: Int) //the model used to test
fun paidMore(amount: Int, employee: Employee,
predicate: (Int) -> Boolean = { _ -> employee.salary > amount }
): Boolean = predicate(amount)
it("judging employee's salary level") {
fun isHighPaid(employee: Employee): Boolean = paidMore(100, employee)
fun isHighPaid2(employee: Employee): Boolean = paidMore(100, employee) {amount ->
employee.salary > amount * 2
}
val employee = Employee("yuri", 101)
assertTrue(isHighPaid(employee))
assertFalse(isHighPaid2(employee))
assertTrue(isHighPaid2(Employee("peter", 201)))
assertFalse(isHighPaid2(Employee("jerry", 200)))
}
}
})
or else
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertFalse
import kotlin.test.assertTrue
object ClosureSpec : Spek({
describe("Test, add a default implementation to the function") {
data class Employee(val name: String, val salary: Int) //the model used to test
//judging employee's salary level
fun Employee.paidMore(amount: Int, predicate: (Int) -> Boolean = {
this.salary > it
}): Boolean = predicate(amount)
on("use the default implementation") {
val amount = 100
fun Employee.isHighPaid() = paidMore(amount)
it("should all be passed") {
assertTrue(Employee("Alice", amount + 1).isHighPaid())
assertFalse(Employee("Alice", amount - 1).isHighPaid())
}
}
on("override the default implementation") {
val amount = 100
fun Employee.isHighPaid() = paidMore(amount) {
this.salary > it * 2
}
it("should all be passed") {
assertTrue(Employee("Bob", amount * 2 + 1).isHighPaid())
assertFalse(Employee("Bob", amount * 2 - 1).isHighPaid())
}
}
}
})
Which one is better? something else? Looking forward to your good idea
0
solved How to simplify the default implementation of a kotlin function