https://kotlinlang.org logo
l

Lilly

03/24/2021, 12:12 PM
Is it possible to define an abstract function as extension function?
Copy code
sealed class Foo {
    abstract fun bar()
}

class A : Foo()
class B : Foo()

/* in another file */

fun A.bar() {
  // implementation
}
It seems it's not possible but maybe there is something similar? I just want to move the implementation of
bar()
to other files because the LOC for the implementation is huge. I want to avoid a file with thousands of LOC. Any ideas?
m

mkrussel

03/24/2021, 12:27 PM
I don't think there is any way to do that. In Kotlin 1.5, you will be able to move class A and class B to different files. You can enable the 1.5 features currently as a preview. https://zsmb.co/sealed-goodies-coming-in-kotlin-1-5/
l

Lilly

03/24/2021, 12:27 PM
ok thanks for the hint 🙂
m

mkrussel

03/24/2021, 12:28 PM
extension methods are implemented as static methods, which is why they cannot override an abstract method.
Another option is to create an internal extension function and then have the bar function call that extension function.
❤️ 1
l

Lilly

03/24/2021, 12:39 PM
Cool idea! I will go with this solution
s

stephanmg

03/24/2021, 1:50 PM
interesting problem