W
W
Way2018-01-27 14:07:18
Java
Way, 2018-01-27 14:07:18

How to convert the given code to kotlin?

Good afternoon, I am rewriting my packages for Kotlin and ran into a problem, namely that it is impossible to assign and return to Kotlin. The code that was:

public class Packet
{
    private ByteBuf buf;

    protected ByteBuf buf()
    {
        return buf != null ? buf : (buf = Unpooled.buffer());
    }

    @Override
    public final void fromBytes(ByteBuf buf)
    {
        this.buf = buf;
    }

    @Override
    public final void toBytes(ByteBuf buf)
    {
        if (buf != null)
            buf.writeBytes(this.buf);
    }
}

Same code but in kotlin.
class Packet
{
    private var buf: ByteBuf? = null

    protected fun buf(): ByteBuf
    {
        return buf ?: ({buf = Unpooled.buffer(); buf}()!!)
    }

    override fun fromBytes(buf: ByteBuf)
    {
        this.buf = buf
    }

    override fun toBytes(buf: ByteBuf?)
    {
        buf?.writeBytes(this.buf)
    }
}

The point is that buf() should not return null, but it turns out that null is returned. What went wrong? How to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Conacry, 2018-01-27
@Conacry

Hello.
Not entirely sure, but if you try this:
return buf ?: Unpooled.buffer()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question