Aviran
Aviran

Reputation: 5458

Mixing Kotlin and Java code

I want to use a Kotlin Android library (FotoApparat) in a Java Android project.

In a Kotlin code base the whenAvailble function gets a kotlin callback as a param, which will be called when the async operation is done.

val photoResult = fotoapparat.takePicture()

// Asynchronously saves photo to file
photoResult.saveToFile(someFile)

// Asynchronously converts photo to bitmap and returns the result on the main thread
photoResult
    .toBitmap()
    .whenAvailable { bitmapPhoto ->
            val imageView = (ImageView) findViewById(R.id.result)

            imageView.setImageBitmap(bitmapPhoto.bitmap)
            imageView.setRotation(-bitmapPhoto.rotationDegrees)
    }

whenAvailable code can be found here

The equivalent java implementation would be: (Previously the library was written in java)

fotoApparat.takePicture().
                    toPendingResult().
                    whenAvailable( /* some sort of call back */);

How do I provide the whenAvailable callback from a Java code?

In previous versions of the lib, there was a Java pending result callback class which no longer available.

Upvotes: 2

Views: 705

Answers (2)

tieskedh
tieskedh

Reputation: 337

Abreslav said:

Unit is a type (unlike void) and has a value (unlike Void). This enable uniform treatment of Unit when it comes to generic classes. I.e. we don’t need another two types: a function that returns something and a function that returns void. It’s all one type: a function that returns something tat may be Unit.

Introducing void would pose many problems in areas like type inference, compositionality of any sort of functions, etc

So, unlike in Kotlin, in Java you need to return this value explicitly.

Your lambda needs to be:

fotoApparat.takePicture().
                toPendingResult().
                whenAvailable(bitmapPhoto -> {
        ImageView imageView = (ImageView) findViewById(R.id.result);
        return Unit.INSTANCE;
});

Upvotes: 5

ice1000
ice1000

Reputation: 6569

Yes you can use something like this:

fotoApparat.takePicture().
                toPendingResult().
                whenAvailable(bitmapPhoto -> {
        ImageView imageView = (ImageView) findViewById(R.id.result);
        // rest of your code
});

Upvotes: 0

Related Questions