Sobes.tech
Junior — Middle

Is it possible to declare a data class with an interface implementation in a programming language?

sobes.tech AI

Answer from AI

In Kotlin, you can declare a data class that implements one or more interfaces. This is often used to create convenient DTOs with additional behavior defined in interfaces.

Example:

interface Printable {
    fun print()
}

data class User(val name: String, val age: Int) : Printable {
    override fun print() {
        println("User(name=$name, age=$age)")
    }
}

fun main() {
    val user = User("Alice", 30)
    user.print()  // Will output: User(name=Alice, age=30)
}

Thus, a data class can implement interfaces without restrictions.