You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Kotlin中缀函数检测左括号'('?类SQL WHERE子句构建

Kotlin构建类SQL WHERE子句:无法检测左括号使用问题

我正在纯Kotlin环境中实现类SQL WHERE子句风格的表达式构建逻辑,目前遇到的核心问题是无法检测用户代码中是否使用了左括号'('。

以下是可运行、可复现的JUnit测试示例:

import org.junit.Assert
import org.junit.Test

class Sample {

    class Expression(private val data: String) {

        var parenthesis = 0 // 负数表示'(', 正数表示')', 0表示无括号

        init {
            if (data == " AND " || data == " OR ") {
                wasAndOr = true
            } else {
                wasAndOr = false
                expressions.add(this)
            }
        }

        companion object {
            val expressions = mutableListOf<Expression>()
            var wasAndOr = false
            fun create(): String {
                val builder = StringBuilder(64)
                expressions.forEach {
                    if (it.parenthesis < 0) for (i in it.parenthesis until 0) builder.append('(')
                    builder.append(it.data)
                    if (it.parenthesis > 0) for (i in 0 until it.parenthesis) builder.append(')')
                }
                return builder.toString()
            }

            fun clear() {
                expressions.clear()
            }
        }

        infix fun and(other: Expression): Expression {
            applyParenthesis(other)
            expressions.add(expressions.indexOf(other), Expression(" AND "))
            return this
        }

        infix fun or(other: Expression): Expression {
            applyParenthesis(other)
            expressions.add(expressions.indexOf(other), Expression(" OR "))
            return this
        }

        private fun applyParenthesis(exp: Expression) {
            if (wasAndOr) {
                exp.parenthesis--
                expressions.last().parenthesis++
            }
        }

        override fun toString(): String {
            return data
        }
    }

    @Test
    fun testParenthesis() {
        (Expression("1") or Expression("2")) and (Expression("3") or Expression("4"))
        Assert.assertEquals("(1 OR 2) AND (3 OR 4)", Expression.create())
        Expression.clear()
    }

    @Test
    fun testWithoutParenthesis() {
        Expression("1") or Expression("2") and (Expression("3") or Expression("4"))
        Assert.assertEquals("1 OR 2 AND (3 OR 4)", Expression.create())
        Expression.clear()
    }

    @Test
    fun testParenthesisLater() {
        Expression("1") or Expression("2") and ((Expression("3") or Expression("4")) and Expression(
            "5"
        ))
        Assert.assertEquals("1 OR 2 AND ((3 OR 4) AND 5)", Expression.create())
        Expression.clear()
    }
}

注:上述为简化演示版本,我的实际代码更为复杂。

内容的提问来源于stack exchange,提问作者Azim Ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 02:22:39