简体   繁体   中英

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.

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. Ie 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;
});

Yes you can use something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM