Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignments are not expressions - Kotlin

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.

like image 429
Mbuodile Obiosio Avatar asked Oct 17 '25 18:10

Mbuodile Obiosio


2 Answers

Change it to:

 mLength = mInput.read(mBuffer)
 while (mLength > 0) { 
        mOutput.write(mBuffer, 0, mLength)
        mLength = mInput.read(mBuffer)
    }
like image 147
Manohar Avatar answered Oct 20 '25 07:10

Manohar


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.

like image 41
Anmol Avatar answered Oct 20 '25 07:10

Anmol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!