Assignments are not expressions - Kotlin

2019-02-25 19:08发布

问题:

I'm refactoring my project built with Java to Kotlin and to copy database from sqlite assets table I'm doing this and it works correctly.

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();
    }

How do I deal with "Assignments are not expressions, and only expressions are allowed in this context"?

@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()
    }

Error is here

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

Thank you.

回答1:

Change it to:

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


回答2:

This is a work around to your problem:

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

For further detail read this discussion.