Created
July 23, 2022 09:27
-
-
Save atr0phy/ec855927c42ac82be1bf3dc56f3049a7 to your computer and use it in GitHub Desktop.
Define generics function in kotlin companion object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.UUID | |
import kotlin.reflect.full.primaryConstructor | |
interface ExampleId { | |
val value: UUID | |
} | |
interface ExampleIdFactory<T: ExampleId> | |
data class HogeId(override val value: UUID): ExampleId { | |
companion object: ExampleIdFactory<HogeId> | |
} | |
data class FugaId(override val value: UUID): ExampleId { | |
companion object: ExampleIdFactory<FugaId> | |
} | |
inline fun <reified T: ExampleId> ExampleIdFactory<T>.of(uuidString: String): T { | |
return T::class.primaryConstructor!!.call(UUID.fromString(uuidString)) | |
} | |
fun main() { | |
val hogeId = HogeId.of("8324a7c5-72b1-44a0-a767-25a1852c14fa") | |
val fugaId = FugaId.of("545f3251-1f95-42c7-8a9a-904c509f32c4") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment