I have a Kotlin/Spring Boot application in which I...
# server
n
I have a Kotlin/Spring Boot application in which I am doing a simple string comparison against a string literal within a list filter. Initially I used
===
, and all of my unit tests passed. However, once deployed, the filter function did not work as expected. I wrote an simple JVM app to see if it was an issue with JVM specifically, but in that case
"str" === "str"
resolved to true, which is not the behavior I was seeing in my Spring Boot app. Any ideas why I'd be seeing this discrepancy in the Spring Boot app?
d
n
Thank you, I have read that documentation, which I interpreted to mean that
it === "str"
would always be false, which is what I was seeing in my Spring Boot app. However, this is not the behavior I was seeing in my unit tests or in the simple JVM console app. My simple JVM console app:
Copy code
class StringListWrapper(val stringList: List<String>) {
    fun goodWordsOnly() = stringList.filter { "GOOD" === it }
}

fun main() {
    val stringWrapper = StringListWrapper(listOf("BAD", "BADDER", "BADDEST", "GOOD"))
    println("${stringWrapper.stringList.joinToString(",")} is unfiltered")
    println("${stringWrapper.goodWordsOnly().joinToString(",")} is filtered")
}
Output:
Copy code
BAD,BADDER,BADDEST,GOOD is unfiltered
GOOD is filtered
d
===
is referential integrity check meaning that both references point to the same object in memory
you most likely want to use
==
which is structural integrity (i.e. whether object contents are equal) -> note: in Java
==
is a referential integrity check vs
.equals
using structural integrity check
google JVM String pools to see whats happening with the String equality
Copy code
val x = "foo"
val y = "foo"

println(x == y)
println(x === y)

val z = String("foo".toByteArray())
println(x == z)
println(x === z)
2
n
i didn't even think to do the equivalent in Java. i replicated it there. it's a Java thing entirely. the strings are being interned in the test run in a way they are not when coming in from an http request. that's ... annoying. 🙂
m
Here is an explanation on why this is happening 😅: https://www.geeksforgeeks.org/string-constant-pool-in-java/
2
c
Basically: just use
==
on strings. Always. If they point to the same reference, it will shortcut and be 0(1). If they don't point to the same reference, it will check the contents, which is O(n).