standinga
11/18/2019, 11:56 PMZach Klippenstein (he/him) [MOD]
11/18/2019, 11:57 PMPlayer
) that returns a Player?
.Shawn
11/18/2019, 11:59 PMcompanion object
that defines operator fun invoke(): Player?
or just a well-named factory method for this particular featurestandinga
11/19/2019, 12:01 AMShawn
11/19/2019, 12:01 AMstandinga
11/19/2019, 12:02 AMHullaballoonatic
11/19/2019, 12:24 AMinterface Player {
val name: String
val verification: Verification?
val isVerified get() = verification != null
companion object {
operator fun invoke(name: String, verification: Verification? = null): Player {
if (verification != null && verification.isNotValid)
throw IllegalArgumentException("Cannot create player with name $name because provided verification is not valid.")
return object : Player {
override val name = name
override val verification = verification
}
}
}
}
This cheeky construction has the full functionality of a class, but can still be implemented freely. You can even achieve "multiple-inheritance" using delegation:
class PlayerEntity(id: UUID, name: String, verification: Verification? = null) : Entity(id), Player by Player(name, verification)
Zach Klippenstein (he/him) [MOD]
11/19/2019, 12:27 AMequals
, hashcode
, and copy
.Hullaballoonatic
11/19/2019, 12:27 AMPlayerEntity
can be the data class, if you fancy that.
more to your point, with this approach, you can't override equals
, hashcode
, or toString
at the interface level, so you'd want to have a basic implementation you always call in the event of multiple "constructors" (read: invoke), and add those Any
functions therestandinga
11/19/2019, 2:53 AMMike
11/19/2019, 11:19 AM