定义没有inheritance的公共属性

有没有在Kotlin中使用inheritance来定义公共属性的方法?

例如

如果我有两个类都需要一个“ID”属性。

class Dog() { var id: UUID? } class Cat() { var id: UUID? } 

解决这个问题的一般JAVA方法是引入一个超级类

 class Animal() { var id: UUID? } class Dog: Animal() class Cat: Animal() 

但是现在“狗”和“猫”是“动物”的types。 如果我介绍一个“主席”类,也需要一个唯一的标识符呢?

本质上,我想创建一组属性的能力,我可以包含在许多不同的类中,以方便编程。 我不希望所有与inheritance有关的问题。

正如在评论中提到的那样:

 interface Animal { var id: UUID? } class Dog: Animal class Cat: Animal 

当然,您可以使用interface而不是基类:

 interface HasId { val id: UUID } data class Dog(override val id: UUID) : HasId data class Cat(override val id: UUID) : HasId 

不过,上面还是使用了inheritance。 如果你有更常见的属性,可能会在多个类中使用它可能是一个标志,他们应该组合在一起,形成一个单独的价值对象,例如

 data class Address(val city: String, val street: String, val country: String) class Person(val name: String, val address: Address) class School(val name: String, val address: Address, val studentsCount: Int) 

如果你想对address属性统一处理人和School ,你仍然可以使用接口来表示共同的属性:

 interface HasAddress { val address: Address } class Person(val name: String, override val address: Address) : HasAddress class School(val name: String, override val address: Address, val studentsCount: Int) : HasAddress 

代表团可能会满足您的需求:

 interface WithId { var id: Int } class IdStorage : WithId { override var id: Int = 0 } class Dog(withId: WithId) : WithId by withId { constructor() : this(IdStorage()) {} } class Cat(withId: WithId) : WithId by withId { constructor() : this(IdStorage()) {} } 

这段代码比较冗长,但是它允许你做的是:

  • 避免仅仅为了拥有id属性而使用超类,这允许您在需要时扩展其他类
  • 接口的使用,保证你的类有id其他代码段
  • 允许将您的属性(或函数)的实现移动到单独的类中,因此在复杂的属性/函数实现的情况下不需要重复的代码
  • 允许在一个单独的类中实现多个属性/函数