Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Interface anonymously in Kotlin results in "has no constructors" error

I'm trying to use a SurfaceView in Android to hold a Camera preview. The documentation tells me that I need to call startPreview in the surfaceCreated callback for the surface holder. I'm trying to set the callback like so

this.surface!!.holder!!.addCallback(SurfaceHolder.Callback() {
    fun surfaceChanged(holder: SurfaceHolder, format: Int, 
                       width: Int, height: Int) {

    }

    fun surfaceCreated(holder: SurfaceHolder) {

    }

    fun surfaceDestroyed(holder: SurfaceHolder) {

    }
})

However, I get the error:

SurfaceHolder.Callback has no constructors.

I'm confused why this doesn't work when something like this does:

Thread(Runnable() {
    fun run() {
        ...        
    }
})
like image 854
robz Avatar asked Jun 02 '17 20:06

robz


1 Answers

To create an object of an anonymous subclass you need to use the object: expression:

this.surface!!.holder!!.addCallback(object: SurfaceHolder.Callback {
    override fun surfaceChanged(holder: SurfaceHolder, format: Int, 
                                width: Int, height: Int) {
        ...        
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        ...
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        ... 
    }
})

and don't forget to use the override keyword per overridden method as well ;)

like image 190
Paulo Mattos Avatar answered Nov 08 '22 07:11

Paulo Mattos