why is not every interface with just one method automatically a functional interface? what advantage...
c
why is not every interface with just one method automatically a functional interface? what advantages does a not functional interface have?
d
Such implicitly easily may lead to not-intended breaking changes Imagine you are library author who introduced some interface with one method with intent to extend it in the future. If it will be considered as
fun
implicitly, then your users may start to use SAM conversion for it, and in future you can't just add another method to it without breaking users. And this situation can be very frustrating, because you originally had no intent to make it
fun
🤔 1
1
c
thanks, makes sense!
j
Isn't adding a function (without default) to an interface a breaking change for inheritors anyway?
No matter whether users used sam conversions or not, they could use anonymous objects too, or their own implementation, all of which would break if a new method is added without a default implementation
c
right. the functional interface will just make it easier to implement the interface right now. and if you change something later, it will break anyway.
j
Yes. But anyway I guess it still makes sense to consciously decide (as an author) whether you expect your interface to be used this way. Because it might fail differently (unresolved reference VS missing method), and it might have different implications for binary compatibility
c
ok but if there was no concept of a “functional interface” and any interface that has only one method could be implemented with the short syntax, what would be the downside?
d
Isn't adding a function (without default) to an interface a breaking change for inheritors anyway?
Yes, indeed 🤦
I found the original reasons: 1.
fun
keyword adds an ability to opt-in/opt-out from the conversion behavior, so you can decide do you want for your interface being used this way or not 2. Language compatibility. Introducing the conversion for all interfaces might break a lot of existing code (back then and now also)
Copy code
fun foo(f: () -> Unit) {} // (1)

class Outer {
    fun interface Sam {
        fun bar()
    }
    
    fun foo(f: Sam) {} // (2)
    
    fun test() {
        // if `Sam` is `fun interface` resolved to (2)
        // otherwise resolved to (1)
        foo { }
    }
}
thank you color 1
e
since Java 8 it is possible to add methods to an interface in an ABI-compatible way, if they have default implementations. so I'd expect be ABI-compatible in Kotlin too in
-Xjvm-default
mode
1