分配不是表达式-Kotlin

时间:2018-07-18 10:33:43

标签: android database sqlite kotlin

我正在将使用Java构建的项目重构为Kotlin,并从sqlite资产表中复制数据库,我正在这样做并且可以正常工作。

private void copyDataBase() throws IOException {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

我该如何处理“赋值不是表达式,在这种情况下只能使用表达式”?

@Throws(IOException::class)
    private fun copyDataBase() {
        val mInput = mContext.assets.open(DB_NAME)
        val outFileName = DB_PATH + DB_NAME
        val mOutput = FileOutputStream(outFileName)
        val mBuffer = ByteArray(1024)
        var mLength: Int
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength)
        }
        mOutput.flush()
        mOutput.close()
        mInput.close()
    }

错误在这里

while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength)
        }

谢谢。

2 个答案:

答案 0 :(得分:2)

将其更改为:

 mLength = mInput.read(mBuffer)
 while (mLength > 0) { 
        mOutput.write(mBuffer, 0, mLength)
        mLength = mInput.read(mBuffer)
    }

答案 1 :(得分:0)

这是解决您的问题的方法:

while ({mLength = mInput.read(mBuffer); mLength}() > 0) {
    mOutput.write(mBuffer, 0, mLength)
}

有关更多详细信息,请阅读this discussion