Edoardo Luppi
05/20/2024, 9:42 AMpublic fun interface Example {
public fun execute(str: String)
}
public class MyClass(example: Example = Example { it + "123" })
What's the reason I can't simply write
public class MyClass(example: Example = { it + "123" })
But I have to specify Example { ... }
?hfhbd
05/20/2024, 12:30 PMEdoardo Luppi
05/20/2024, 12:31 PMExample
?hfhbd
05/20/2024, 1:18 PMfun interface A {
fun a(): String
}
fun interface B : A {
override fun a(): String {
return "ASDF + ${b()}"
}
fun b(): String
}
fun main() {
val a: A = A {
"Hello A"
}
println(a.a())
val b: B = B {
"Hello B"
}
println(b.a())
val c: A = B {
"Hello C"
}
println(c.a())
if (c is B) {
println(c.b())
}
}
Edoardo Luppi
05/20/2024, 1:20 PMhfhbd
05/20/2024, 1:22 PMEdoardo Luppi
05/20/2024, 1:23 PMKlitos Kyriacou
05/20/2024, 1:28 PMfun foo(a: A) {
a.a()
}
then the compiler allows us to pass an implicit A
instance, even if it was actually a B
. All of these lines will compile ok:
foo { "Hello" }
val b: B = B { "Hello" }
foo(b)
foo(B { "Hello" })
So I guess the OP's question is why can you pass an A
implicitly as a function parameter, but not as a default parameter?hfhbd
05/20/2024, 1:35 PMval a: A = { // error: required A, found: () → String
"Hello"
}
So this syntax "should" be supported too and not only for default parameters.Edoardo Luppi
05/20/2024, 1:36 PMEdoardo Luppi
05/20/2024, 1:36 PMKlitos Kyriacou
05/20/2024, 1:39 PM