https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

MarkRS

01/19/2022, 4:06 PM
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

Rob Elliot

01/19/2022, 4:10 PM
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

ephemient

01/19/2022, 4:43 PM
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

MarkRS

01/19/2022, 5:14 PM
Yes @Rob Elliot, a typo (now corrected) there might've given the wrong impression. @ephemient, I'll try that now.
k

Klitos Kyriacou

01/19/2022, 5:20 PM
What's wrong with your original code?
m

MarkRS

01/19/2022, 5:21 PM
@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

Klitos Kyriacou

01/19/2022, 5:24 PM
Your code works just fine: https://pl.kotl.in/6uAPiAVzB
m

MarkRS

01/19/2022, 5:30 PM
@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

Klitos Kyriacou

01/19/2022, 5:53 PM
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

MarkRS

01/19/2022, 6:31 PM
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.
2 Views