Suppose I have: ``` abstract class AbstractClass ...
# getting-started
m
Suppose I have:
Copy code
abstract class AbstractClass (
  val a : String? = null,
  val b : String? = null,
  val c : String? = null,
  val d : String? = null,
  val e : String? = null,
  val f : String? = null,
  val g : String? = null
)

class MyClass (
  a, b, c, d, e, f, g,
  val h : String? = null,
  val i : String? = null
) : AbstractClass(
  a, b, c, d, e, f, g
)
Is there any kind of shorthand to avoid having to repeat a,b,c,d,e,f,g twice when defining the class?
🚫 2
k
Not right now, there's this feature request for this: https://youtrack.jetbrains.com/issue/KT-15471
m
OK, thanks. I think for now I'm going to give up immutability.
k
Would it be possible to use compostion, don't inherit from baseclass but take it as a parameter instead?
Or do both and create an extra argument wrapping class.
Immutability is so nice 🙂
m
I guess that would be another option, yes, though then that would complicate field access.
Unless I provided accessors, and then you're back to having to add a whole bunch of code...
u
Can’t you create an interface with the fields and use interface delegation to simplify adding the fields.
Copy code
interface MyInterface {
    val a: String?
    val b: String?
}

class Base(
    override val a: String? = null, 
    override val b: String? = null
) : MyInterface

class MyClass(
    base: MyInterface,
    val c: String? = null
) : MyInterface by base
It’s a little bit more code to implement your example but when adding more subclasses it will substantially less.
j
Not a shorthand, but in case you weren't aware, you can make typing things like that much much faster using multicursor editing (https://blog.jetbrains.com/phpstorm/2014/03/working-with-multiple-selection-in-phpstorm-8-eap/) in IntelliJ.
j
The difficulty you are feeling with this class that has about 10 collaborators, is that it has 10 collaborators! This is a strong signal that your code could be refactored. I'm assuming that this was an example, but it's also highly error prone to have many arguments of the same type - it's too easy to transpose them without noticing.
Accessing fields is also kind of an anti pattern - "getters and setters" is very much an enterprise java hang over. OO is much more about "tell dont ask". You can safely use public access if fields are immutable if you need to, as long as you avoid "train-wreck" a..b.c.d() law of Demeter violations.
Additionally, having so many things nullable can indicate that it may be hard to know exactly what state the object is in. There is combinatorial complexity in all the optionality!
m
The class in question is for holding data corresponding to a SQL database row and a noSQL document, and translating between the two. So unfortunately the large number of nullable fields is a requirement.