Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Type of 'exoPlayer' doesn't match the type of the overridden var-property 'public abstract var exoPlayer: ExoPlayer? defined in

Tags:

kotlin

I am not sure I understand what is going on here. Please could someone explain?


I get the following error: Type of 'exoPlayer' doesn't match the type of the overridden var-property 'public abstract var exoPlayer: ExoPlayer? defined in...

when I compile:

class LocalPlayback(context: Context, override var exoPlayer: SimpleExoPlayer?) : Playback {
    private val context: Context
    //... other stuff...
    }

where LocalPlayback extends Playback:

interface Playback {
    var exoPlayer: ExoPlayer?
    //... other stuff...
    }

SimpleExoPlayer implements the ExoPlayer interface.

like image 366
Lisa Anne Avatar asked Oct 23 '25 18:10

Lisa Anne


2 Answers

A var allows both getting and setting of a value. Overriding a var with a var of a more specific type is not possible in a type-safe way because using the super-type, they could set the value to a more general type, and then when someone uses the overridden var, it would be of the wrong type. By changing the super-type to have a val, it prevents being able to set it to a general type, which eliminates the issue.

like image 50
Eric Pabst Avatar answered Oct 26 '25 14:10

Eric Pabst


You need to declare your exoPlayer variable as val in interface and everything would be ok.

interface Playback {
    val exoPlayer: ExoPlayer?
    //... other stuff...
    }

I made an example to test:

    interface Playback {
        val exoPlayer: ExoPlayer
    }

    class LocalPlayback(override var exoPlayer: SimpleExoPlayer) : Playback 

    open class ExoPlayer
    class SimpleExoPlayer : ExoPlayer()

It compiles well. Maybe someone else could help us with explanation.

like image 28
A. Shevchuk Avatar answered Oct 26 '25 15:10

A. Shevchuk