kotlinconstructorinterfaceadapter

Can i use an interface type as constructor parameter in Kotlin


Coming from Java, I define two interfaces for triangles:

interface TriangleA {
    val side: Double
    val corner1: Double
    val corner2: Double
}

interface TriangleB {
    val side1: Double   
    val side2: Double   
    val side3: Double   
}

Then I define an adapter class that accepts a TriangleB and exposes a TriangleA

class TriangleBAdapter(triangleB:TriangleB):TriangleA{

    override val side: Double
        get() = this.triangleB.side

    override val corner1: Double
        get() = TODO("Not yet implemented")

    override val corner2: Double
        get() = TODO("Not yet implemented")
}

Why isn't this valid Kotlin? I get an "Unresolved reference: triangleB" error.


Solution

  • Right now triangleB is just a constructor parameter. In Java, this would look like this:

    class TriangleBAdapter implements TriangleA {
    
        public TriangleBAdapter(TriangleB triangleB) {
            // does nothing!
        }
    
        @Override
        public double getSide() {
            return triangleB.side; // error!
        }
    
        ...
    }
    

    You need to make triangleB also be a property, kind of like doing this in Java:

    private final TriangleB triangleB;
    public TriangleBAdapter(TriangleB triangleB) {
        this.triangleB = triangleB;
    }
    

    You can do this by adding val in front of it, and optionally also private:

    class TriangleBAdapter(private val triangleB: TriangleB): TriangleA {
    
        override val side: Double
            get() = this.triangleB.side1
    
        ...
    }