robfletcher / strikt

An assertion library for Kotlin
https://strikt.io/
Apache License 2.0
555 stars 61 forks source link

Using get with lambdas can cause false results #249

Open mstachniuk opened 3 years ago

mstachniuk commented 3 years ago

I really like syntax "get with lambdas" but it can cause false results or mislead when local variable has the same name as field in subject. See example:

import io.kotest.core.spec.style.ShouldSpec
import strikt.api.expectThat
import strikt.assertions.isEqualTo

class ATest: ShouldSpec({
    context("Example") {
        should("fail") {
            val name = "David"                      // (1)
            val subject = Person("Ziggy")
            expectThat(subject) {
                get { name } isEqualTo "David"
            }
        }
    }
})

data class Person(
    val name: String
)

In above example get { name } is not taken from the subject, but from the local value (1). The framework should prevent such wrong usage! I know there is a syntax get(Person::name) but it's not so nice like get with lambda.

cloudshiftchris commented 2 years ago

there's an alternate Kotlin syntax for referencing variables where they exist in multiple contexts: this@