Search code examples
androidkotlininterfacecallback

Is it possible not to override methods from the interface?


I have a class:


class CameraFragment : Fragment() {

    interface CameraResultReturner {
        fun returnCameraBarcode(result: String)
        fun returnCameraBitmap(result: Boolean)
        fun returnCameraBitmapAndBarcode(result: String, bitmap: Bitmap?)
    }

There is a class that receives a response from CameraFragment

class TaskLinkFragment : Fragment(R.layout.fragment_task_link),
    CameraFragment.CameraResultReturner,
    BarcodeInfoFragment.BarcodeInfoListener,
    BarcodeListFragment.BarcodeListListener {

Accordingly , three methods appear in TaskLinkFragment

override fun returnCameraBarcode(result: String) {
//does nothing
    }

override fun returnCameraBitmap(result: Boolean) {
//does nothing
    }

override fun returnCameraBitmapAndBarcode(result: String, bitmap: Bitmap?) {
       //does something
    }

Is it possible to get rid of unused methods in this class, given that they are used in other classes?

Nothing comes to mind.


Solution

  • Instead of adding open modifier, I'd recommend you to add default implementation for these functions

    interface CameraResultReturner {
        // Empty implementation
        fun returnCameraBarcode(result: String) = Unit
    
         // Empty implementation
        fun returnCameraBitmap(result: Boolean) = Unit
    
        // Empty implementation
        fun returnCameraBitmapAndBarcode(result: String, bitmap: Bitmap?) = Unit
    }
    
    
    class MyCameraResultFragment : CameraResultReturner {
        // No need to override the methods, as they already have empty implementations
    }