https://kotlinlang.org logo
Title
h

hfhbd

02/21/2022, 7:25 PM
Why is this not possible:
fun interface A {
    fun foo(b: Int = 42) // Single abstract member cannot declare default values
}
u

Umar Ata

02/21/2022, 7:32 PM
since you written fun in the prefix of interface therefore it is causing issues
h

hfhbd

02/21/2022, 7:35 PM
Yes, I want to keep the
fun
modifier to use it as a
FunctionalInterface
A { }.foo()
u

Umar Ata

02/21/2022, 7:41 PM
I am not sure if it is allowed for interface
j

Joffrey

02/22/2022, 12:08 AM
@Umar Ata
fun interface
is valid and defines functional interfaces
@hfhbd to be honest I don't know, but I guess it may have to do with the fact that it wouldn't know how to convert the interface into a function: it could be either a
() -> Unit
or a
(Int) -> Unit
, and I guess that ambiguity could cause problems during SAM conversions
h

hfhbd

02/22/2022, 12:29 AM
@Joffrey What do you mean? The parameter of the body?
A { i -> // this?

}
Even with default values in the definition (the interface), you still would need to declare the variables in the body, implementation. If you mean calling the (single) member
foo
, the compiler is able to infer the correct overload, like its normal behavior with default values. Or do you mean this:
val a: (Int) -> Unit = A { }
? This does not compile, because even a
fun interface
does not inherit from
KFuction
(and its
invoke
) by default.
j

Joffrey

02/22/2022, 12:31 AM
I meant the very last part: using an instance of the fun interface where a function is expected. I thought SAM conversions were supposed to work in that case, but I guess I was wrong