thesame
thesame

Reputation: 133

Returning interfaces from methods

In Vala programming language is there a way to declare an interface method that returns an object implementing an interface? For example, if I need a method that reads something from somewhere, I declare it like this:

interface SeekableInput: GLib.InputStream, GLib.Seekable {}

interface Reader {
  SeekableInput read();
}

And now I want to implement a Reader that just reads from memory into MemoryInputStream, which is actually an InputStream implementing Seekable according to its documentation.

class MemoryReader: Reader {
  GLib.MemoryInputStream _stream;

  // This produces "... overriding method ... is incompatible ... expected return type ...":
  GLib.MemoryInputStream read() { return _stream; }

  // This produces "Cannot convert from ...":
  SeekableInput read() { return _stream; }
}

I can't declare read() to return MemoryInputStream because there would be another Reader reading into BufferedInputStream.

Upvotes: 1

Views: 71

Answers (2)

sergej.dobryak
sergej.dobryak

Reputation: 11

I think you need here a wrapper for your GLib.MemoryInputStream to compile without errors:

interface SeekableInput: GLib.InputStream, GLib.Seekable {}

interface Reader {
    SeekableInput read();
}

class MemorySeekableInput: SeekableInput {
    private GLib.MemoryInputStream stream;

    public MemorySeekableInput(GLib.MemoryInputStream stream){
        this.stream = stream;
    }

    // ... implement all abstract methods for InputStream and Seekable
}

class MemoryReader: Reader {
    GLib.MemoryInputStream _stream;

  SeekableInput read() { return new MemorySeekableInput(_stream); }
}

your code won't compile, because SeekableInput is a new unique type and it is not equal to GLib.MemoryInputStream type, even if it implements InputStream and Seekable

Upvotes: 0

AlThomas
AlThomas

Reputation: 4299

It's called casting. Something like this should work:

class MemoryReader: Reader {
  GLib.MemoryInputStream _stream;

  SeekableInput read() { return (SeekableInput)_stream; }
}

Upvotes: 1

Related Questions