Skip to content

Instantly share code, notes, and snippets.

@j-didi
Last active June 10, 2020 22:50
Show Gist options
  • Save j-didi/1beee9c3e58757f9076959663210b469 to your computer and use it in GitHub Desktop.
Save j-didi/1beee9c3e58757f9076959663210b469 to your computer and use it in GitHub Desktop.
Using generics constrains to manipulate base class properties
import java.time.LocalDateTime
import java.util.UUID.randomUUID
abstract class EntityBase {
lateinit var id: String
lateinit var createAt: LocalDateTime
lateinit var lastUpdateAt: LocalDateTime
}
class Person(val name: String) : EntityBase()
interface Repository<T> { fun save(entity: T) : T }
class RepositoryImpl<T> : Repository<T> where T: EntityBase { //EntityBase Constraint
override fun save(entity: T): T {
val now = LocalDateTime.now()
//EntityBase properties manipulation
entity.apply {
id = randomUUID().toString()
createAt = now
lastUpdateAt = now
}
//save implementation...
return entity
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment