Partial classes?


#1

If Kotlin supports compile class "namespace" in different files, it means that the class of "namespace" is a partial class. Why not extend this capability to other classes in the module? For example

// generated/MyClass.kt
partial class MyClass {
  val one: Int = 1
}

// hand-written/MyClass.kt

partial class MyClass {
  val two: Int = 2
}

fun test() {
  val myClass = MyClass()
  myClass.one = -1
  myClass.two = -2
}

P.S.
Trait as an argument not taken into account. These are different things.


#2

The "namespace" class is not a class from the language perspectivew, only from the runtime perspective. So, "extend this capability" is a little bit of an exaggeration here :)


#3

Anyway, it would be nice to have this feature. Partial classes are partial only before and during the compilation. This is true only for classes from the source code within a module. At runtime, they are no longer partial.


#4

What is a use case of partial classes? When can't be they be replaced with inhertance?


#5

Why use inheritance when you don't need it or want it?  I think the point of partial classes if you want to have some generated code (which lives in a different file) be part of a class.  This could be useful in either something like a generated model classes that an ORM tool may generate, or like ASP.NET does with code-behind files.  It's all about tool integration as I see it, not about writing code manually.


#6

The only somewhat valid justification for Partial Classes existence is code generation, but often that has its own problems. I'd be really against have partial classes in Kotlin. Many times it's nothing but an excuse to violate SRP.


#7

Is this not somewhere where you'd use traits? Make your generated code a trait and just mix it into your normal class...


#8

If you don't need state, traits are fine


#9

I was just remembering an old/existing bug in Kotlin where code in the namespace will break if you do it in both say src/main/kotlin and src/test/kotlin - as you'll end up with ONLY the src/test/kotlin variation of the class.

If such a “class extension” mechanism was to work we could solve this.  However - adding partial classes REALLLLLLY brings in horrible issues when it comes to modularity/dependency management.