如何修复 "lateinit property YYY has not been initialized"

How to fix "lateinit property YYY has not been initialized"

我有一个 class 可以建立蓝牙连接并从连接在汽车中的 OBD 蓝牙加密狗获取 PID。 但是当调用获取 RPM 的方法时,我有一个关于不初始化 属性.

的异常
class BluetoothOBDManager : OBDManager {
    lateinit var context: Context
    private lateinit var input: InputStream
    private lateinit var output: OutputStream
    private lateinit var rpmCommand: RPMCommand
    private lateinit var coolantTempCommand: EngineCoolantTemperatureCommand
    private lateinit var airIntakeTempCommand: AirIntakeTemperatureCommand
    private lateinit var mmSocket : BluetoothSocket

    fun connect(deviceString: String) {
        var adapter: BluetoothAdapter = getDefaultAdapter()
        val device = adapter.getRemoteDevice(deviceString)
        val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
        val mmSocket:BluetoothSocket=device.createRf....Record(uuid)

        mmSocket.let { socket ->
                socket.connect()
            }

        input = mmSocket.inputStream
        output = mmSocket.outputStream
        if (mmSocket.isConnected) {
            println("output.write =1")
            output.write(1)
        }
        rpmCommand = RPMCommand() //This is the INIT of the propert
    }

    override fun getCurrentRpm(): Int {
        rpmCommand.run(input, output) // This line throughs the EXCEPTION
        return rpmCommand.rpm
    }
}

我就是这样调用另一个方法的class

BluetoothOBDManager().connect(deviceString)
            var rpm  = BluetoothOBDManager().getCurrentRpm()
            rpmTextView.setText(rpm)

异常

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: gr.obd.logger, PID: 17486
    kotlin.UninitializedPropertyAccessException: lateinit property rpmCommand has not been initialized

我尝试在方法中初始化 属性 但没有成功

  override fun getCurrentRpm(): Int {
        rpmCommand = RPMCommand()
        rpmCommand.run(input, output) // This line throughs the EXCEPTION
        return rpmCommand.rpm
    }
BluetoothOBDManager().connect(deviceString)
        var rpm  = BluetoothOBDManager().getCurrentRpm()

您的代码创建一个 BluetoothOBDManager,连接它(初始化 rpmCommand),然后丢弃它,创建一个 new BluetoothOBDManager一切都未初始化并尝试调用 getCurrentRpm 。应该是

val obdManager = BluetoothOBDManager()
obdManager.connect(deviceString)
val rpm = obdManager.getCurrentRpm()

这并不能解释为什么你会得到

I have tried to INIT the property inside the method but no luck

但是真的不应该发生;我预计会出现其他问题。