https://kotlinlang.org logo
Title
l

luke_c

10/23/2018, 3:24 PM
How does default parameters in interfaces work? The IDE complains if you try to implement the interface function with the default parameter but it doesn’t seem to mind if you leave it out
s

Shawn

10/23/2018, 3:29 PM
would you mind sharing a minimal snippet demonstrating the behavior you’re seeing?
@luke_c (just in case you don’t get thread notifications)
e

Egor Trutenko

10/23/2018, 3:35 PM
It's because by defining default params you violate abstraction which interfaces provide. For example:
interface Interface {
    fun someFun(p: Int)
}

class Impl: Interface {
    override fun someFun(p: Int = 1) {
        ...
    }
}

val i: Interface = Impl()
i.someFun()
You expect that in the last statement
someFun
will be invoked with default parameter value (that is,
1
), but
i
is of type
Interface
and thus its function needs to be supplied with some value, because compiler uses definition from
Interface
, not
Impl
.
h

hho

10/23/2018, 3:42 PM
Yeah, the compiler doesn't allow any default values when overriding a function – even when you attempt to override with the same value.
l

luke_c

10/23/2018, 3:44 PM
It works as I would expect to be fair, the default value still works, it’s just a bit confusing when you look at the method signatures
It would make more sense to me if the signatures had to be the same