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

如何在Kotlin中获取局部符号表?求Python locals()等效实现

Kotlin中Python locals()函数的等效实现方案

核心结论

Kotlin作为静态类型语言,没有直接对应Python locals() 的函数。locals()是Python这类动态语言的特性,能在运行时获取当前作用域的局部符号表;而Kotlin在编译阶段就确定了变量类型与作用域,运行时无法直接获取函数内的局部变量集合。

针对你的Python代码翻译方案

你的Python代码通过闭包内的局部变量(interest、__init__、deposit、withdraw)动态生成Account类,在Kotlin中可以通过常规的类定义实现相同逻辑,不需要依赖动态符号表:

基础实现(贴近Kotlin常规写法)

class Account(private var holder: String, private var balance: Double = 0.0) {
    companion object {
        private const val interest = 0.02
    }

    fun deposit(amount: Double): Double {
        balance += amount
        return balance
    }

    fun withdraw(amount: Double): Any {
        return if (amount > balance) {
            "Insufficient funds"
        } else {
            balance -= amount
            balance
        }
    }
}

// 使用示例
fun main() {
    val account = Account("Alice")
    println(account.deposit(100.0)) // 输出100.0
    println(account.withdraw(50.0)) // 输出50.0
    println(account.withdraw(60.0)) // 输出Insufficient funds
}

模拟原代码的动态属性管理

如果需要贴近原代码中self['get']/self['set']的属性操作逻辑,可以用MutableMap存储属性:

class Account(accountHolder: String) {
    companion object {
        private const val interest = 0.02
    }
    private val properties = mutableMapOf(
        "holder" to accountHolder,
        "balance" to 0.0
    )

    fun deposit(amount: Double): Double {
        val newBalance = (properties["balance"] as Double) + amount
        properties["balance"] = newBalance
        return newBalance
    }

    fun withdraw(amount: Double): Any {
        val balance = properties["balance"] as Double
        return if (amount > balance) {
            "Insufficient funds"
        } else {
            properties["balance"] = balance - amount
            properties["balance"] as Double
        }
    }

    // 可选:添加get/set方法还原原代码逻辑
    fun get(key: String): Any? = properties[key]
    fun set(key: String, value: Any) {
        properties[key] = value
    }
}

内容的提问来源于stack exchange,提问作者rakesh s

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:43:11