How do I create a class to inherit from a class th...
# getting-started
m
How do I create a class to inherit from a class that can either take an instance of itself or nothing as an initialiser? I had assumed
Copy code
class childClass(child: childClass?) : parentClass(child) {
    constructor() : this( null)
but this breaks when calling it as childClass(). The parent class I'm trying to inherit from is a Java class, "Path" from android.graphics, but I assume that doesn't matter. I've checked that code and it claims to accept a null.
r
Do you mean this?
Copy code
class ChildClass(child: ChildClass? = null) : ParentClass()
or this?
Copy code
class ChildClass(child: ChildClass?) : ParentClass() {
    constructor(): this(null)
}
Or do you need to pass
child
to the ParentClass's constructor:
Copy code
class ChildClass(child: ChildClass? = null) : ParentClass(child)
e
only use primary constructors if every construction can use the same super constructor. doesn't sound like it's the case here, so you may need to
Copy code
class Child : Parent {
    constructor() : super()
    constructor(p) : super(p)
m
Yes @Rob Elliot, a typo (now corrected) there might've given the wrong impression. @ephemient, I'll try that now.
k
What's wrong with your original code?
m
@Klitos Kyriacou It crashes when I try to create childClass without a parameter ( childClass()" )
Many thanks @ephemient, yes, that seems to do the trick!
k
Your code works just fine: https://pl.kotl.in/6uAPiAVzB
m
@Klitos Kyriacou, hmmm. That play won't let me modify it by making android.graphics.Path the parent class, but that is my case, and it crashes. Perhaps Path isn't an open class and perhaps that makes the difference?
k
Path is a non-final Java class, which means it's an open class. But I think the problem might be that calling
Path(null)
, albeit valid in itself, causes a crash somewhere down the line. If you want to create an empty Path then you need to call
Path()
which is very different to
Path(null)
.
m
The code (that the AS debugger showed me) for path has code to handle null as a parameter, however it crashes. Dunno why, it looks like it shouldn't. However, I can see you're right that Path() is different from Path(null). and @ephemient’s correction makes it work.