为什么即使 arrayListOf 包含 `foo in list` 也返回 false?

Mah*_*lam 0 kotlin

我正在尝试用 Kotlin 编写的这段代码(我是 Kotlin 的初学者)。我希望收到“真”但是我收到了“假”即使listo包含它。这是我的代码:

fun main(args: Array<String>) {
    class product(var product: String, var productName: String)
    val listo = arrayListOf(
            product("shirt", "yoyo")
    )
    val testing = product("shirt", "yoyo")
    if (testing in listo) {
        println("True")
    } else {
        println("False")
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?任何帮助真的很感激

小智 5

product类不重写equals,所以它做一个对象实例的比较方法和两个列表中包含不同的对象。

您可以声明productwith data class product(...which auto 生成equals将比较两个字符串属性的方法,这意味着listo将包含testing. 它还生成了许多其他方便的方法。

https://kotlinlang.org/docs/reference/data-classes.html