Reputation: 465
I've got a data class in Kotlin:
data class Image (val name: String, val url: URL) {}
I want to serve a list of these Images via REST (Spring Boot, JPA), but I just want certain properties (in this example just the names, not the URLs) to be served. From what I have read I need to use a projection - define an interface with just a 'getName' function:
interface HasName {
fun getName () : String
}
..then set the data class to implement this, and get the RestController to serve HasNames rather than Images:
@GetMapping("/images")
fun getImages () : List <HasName> {
return imageService.getImages()
}
(or that's what I'd do in Java anyway).
However, if I do this in Kotlin:
data class Image (val name: String, val url: URL) : HasName {}
I get an error:
Accidental override: The following declarations have the same JVM signature (getUrl()Ljava/net/URL;):
public final fun
<
get-url>
(): URL defined in com.figmentsignage.server.data.campaign.Image public abstract fun getUrl(): URL defined in com.figmentsignage.server.data.campaign.Image
Is there an easy way around this? I can give the method a different name and redefine it in the Image class, but that's a bit messy. Or I can define the 'name' variable in the interface and override it in the Image, again messy. I ideally want to change the Image class as little as possible.
Upvotes: 0
Views: 1409
Reputation: 607
Here's how I'd define these in kotlin, just using a name
property (no need for a getName()
method) and being sure to use the override
keyword:
interface HasName {
val name: String
}
data class Image(override val name: String, val url: URL): HasName
Upvotes: 7