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

为何出现“firstTime的值始终为true”报错?如何将其改为false?

问题原因

firstTime 是 test() 函数的局部变量,每次调用 test() 时,这个变量都会被重新声明并初始化为 true。编译器能分析出,每次进入函数后,if(firstTime) 的条件永远成立,else 分支完全不会被执行,因此抛出“value of 'firstTime' is always true”的提示(这是编译器的逻辑冗余警告,并非运行时报错)。

解决方法

要让 firstTime 在多次调用 test() 之间保留状态,需要把它从函数局部变量改为跨调用持久化的变量,常见实现方式如下:

1. 顶层变量

将 firstTime 声明在函数外部,作为顶层变量,其生命周期与程序一致:

var firstTime = true

fun test(){
    if(firstTime){
        print("Foo")
        firstTime = false
    } else {
        print("Bar")
    }
}

test() // 输出 Foo
test() // 输出 Bar

2. 类成员/伴生对象变量

如果 test() 是类的成员函数,可将 firstTime 放在伴生对象(全局唯一)或类成员(每个实例独立)中:

class TestHandler {
    companion object {
        var firstTime = true
    }

    fun test(){
        if(TestHandler.firstTime){
            print("Foo")
            TestHandler.firstTime = false
        } else {
            print("Bar")
        }
    }
}

val handler = TestHandler()
handler.test() // 输出 Foo
handler.test() // 输出 Bar

3. 线程安全实现(多线程场景)

如果需要在多线程环境下使用,建议用 AtomicBoolean 避免并发问题:

import java.util.concurrent.atomic.AtomicBoolean

val firstTime = AtomicBoolean(true)

fun test(){
    if(firstTime.compareAndSet(true, false)){
        print("Foo")
    } else {
        print("Bar")
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:00:04