Partial Class support in the future?


#1

Since Kotlin is able to create top level function inside a package, but since it will just be compiled as a package class, then why not try to support partial class just like in C#? Cause it will benefit a lot since it can be extended anywhere and also much cleaner approach.


#2

I'm curious, what would beyour use case? Can it be achieved with extension functions?


#3

Extension method (plus): + Can extend anything on the fly (class, object, trait)

Extension method (minus):

  • Can’t do static extend since it’s only for instance (actually it can by extending the respetive Companion)
  • Will have to import the method, mostly manually since IDE sometimes can’t import it automatically.

Top-level function (plus):

  • Can call the method without instatiating the “hidden” class

Top-level funtion (minus):

  • Can’t change the “hidden” class name since it will always be compiled into xxxPackage class name. So not so great when calling it from Java.

Partial declaration (class, object, trait)

  • Better entity naming, no longer xxxPackage name
  • Basically it just declaration, so it should able to create (extend) static member and instance member

Those 3 things (extension, top-level funtion, partial declaration) will complement each others.


#4

I already use extension method a lot.

loggable.kt
trait Loggable {
  fun info() { … }
  fun error() { … }
}

hello.kt
object hello : Loggable {}

world.kt
fun hello.world(message: String) {
  this.log().info(message)
}

main.kt
{
  hello.world()
}

if Partial declaration is supported, I don’t have to create an empty declaration like in hello.kt, since I can “extend” it anywhere.

world.kt
partial object hello : Loggable {
  fun world() { … }
}

name.kt
partial object hello {
  fun name() { … }
}

or when using it as class, should be able to declare static member anywhere.

name.kt
partial class hello {
  companion object {
  fun name() { … }
  }
}

I think top-level function already did this but minus the naming ability.


#5

Partial classes are great for code generation because the generated code can go in a separate file from the hand-written code but it's still in the same class.

In Java you have to choose between two bad options. You can mix the hand-written and generated code which is normally ugly, or you can generate code into a different class which has limitations. The combination of partial classes and annotation processing for code generation would be extremely powerful.


#6

partial class helps organize big class in a proper logic way.
actually ,in my iOS project ,I have a controller class consist with more than 9 files.
one main feature one extension class file. hope kotlin will support partial class,or extension class more friendly