0

I've got a Kotlin class, similar to

data open class MyDto (
var property: String? = null
// ...
)

and a Java class extending this class, similar to

class MySpecificDto extends MyDto {
    private String field; 
    // getter/setter for "field"
    public MySpecificDto(final MyDto prototype)
    {
        super(prototype);
    }
}

What is missing in Kotlin's DTO for the "super(prototype)" statement to compile?

Alex
  • 8,245
  • 8
  • 46
  • 55

1 Answers1

2

MyDto's constructor takes a single parameter of type String, and you are trying to pass it a MyDto.

I think you are looking for --

super(prototype.getProperty());

Data classes seem a like logical base for a hierarchy of DTOs. Unfortunately, they do not play well with inheritance, so doing so is not a good idea. See this answer.

Update to address comment --

For a Kotlin side solution, you need to remember Kotlin classes only allow for a single constructor. For data classes, the format of that constructor is already defined, so you cannot just pass an object and have it work, or define a different constructor. Also, as noted by @bashor in comment to your original question, there is no copy constructor. You can, however, create a separate function to initialize your object if you want --

data open class MyDto (var property: String? = null //...) {
    fun init(dto: MyDto) {
        property = dto.property
        //... rest of the properties
    }
}

and the in your Java constructor call init instead of super.

public class MySpecificDto extends MyDto {
    private String field;

    public MySpecificDto(final MyDto prototype)
    {
        init(prototype);
    }
}

The caveat on this solution is that your data class must provide default values for all of its properties because there is an implicit call to the constructor with zero parameters.

Community
  • 1
  • 1
iagreen
  • 31,470
  • 8
  • 76
  • 90
  • super(prototype.getProperty()) passes just a single property to a constructor but I want to pass an entire prototype object that contains many properties. Also I'm looking for a solution in Kotlin code, not in Java code. – Alex Nov 25 '14 at 06:33