I have an interface that must return itself: ```in...
# getting-started
c
I have an interface that must return itself:
Copy code
interface Foo {
    fun foo(): Foo
    fun bar(): Foo
}
Ideally, it would use self-types, but since we don't have that, instead each implementation must override the return types with itself.
Copy code
class FooA {
    override fun foo(): FooA
    override fun bar(): FooA
}

class FooB {
    override fun foo(): FooB
    override fun bar(): FooB
}
In reality though,
Foo
has a dozen functions that have a default body. Because of that, I don't get a compilation error if I forget to override them. Do you have any tricks that would make it easier to detect when an implementation is missing an override?
h
Copy code
public interface Foo<out T: Foo<T>> {
    public fun foo(): T
    public fun bar(): T
    public fun baz(): T {
        
    }
}
j
Two options interface Foo<SELF : Foo<SELF>> { fun self(): SELF fun foo(): SELF fun bar(): SELF = self() // default bodies can still work maybe } class FooA : Foo<FooA> { override fun self() = this override fun foo() = this } Or use classgraph to check all the implementations?
Maybe!!
c
^ works, but it can't strictly require you to have the type parameter match the class itself. For example, this compiles just fine:
Copy code
interface Foo<T: FooT> {
    fun foo(): T { return this as T }
    fun bar(): T { return this as T }
}

class FooA : FooFooA {
    override fun foo(): FooA { TODO() }
    override fun bar(): FooA { TODO() }
}
class FooB : FooFooA {
    override fun foo(): FooA { TODO() }
    override fun bar(): FooA { TODO() }
}
c
That kind of self-type emulation doesn't solve the issue because the real hierarchy much more complex, for example:
Copy code
interface FooT {
    fun foo(): FooT
    fun A map(…): FooA
}
To use self-type emulation here, I'd need higher-kinded types, which we don't have
j
Maybe try the classgraph option?
c
Thanks, I'll explore that
y
If they're returning copies, you're SoL If it's just returning
this
, you can make the interface methods return Unit, and provide extensions that are generic on the receiver type
c
it's copies 🙂
But it's not that much code and they don't change often, I just want the build to fail if I forgot one, it's fine to write them manually
m
A couple of tricks which abuse our diagnostics, I'm not sure they are worth it, but you could do smth along these lines snowball hehe
Copy code
interface DefaultFoo {
  fun foo(): DefaultFoo = this
}

interface MustOverrideFoo : DefaultFoo {
  abstract override fun foo(): MustOverrideFoo
}

class Bad : MustOverrideFoo {
  override fun foo(): Bad = this
}
Copy code
interface DefaultFoo {
  fun foo(): DefaultFoo = this
}

interface RequiresFoo {
  fun foo(): DefaultFoo
}

class Good : DefaultFoo, RequiresFoo {
  override fun foo(): Good = this
}
➕ 1