Last active
October 17, 2018 07:17
-
-
Save mike-neck/aaf794e7cdfabd54a137ef476e36816f to your computer and use it in GitHub Desktop.
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
enum class TalkType { | |
PAIR, GROUP | |
} | |
data class Talk(val id: Int, val type: TalkType, val name: String?, val users: List<String>) | |
sealed class TalkBuilderState | |
object IdOfTalk: TalkBuilderState() | |
object TypeOfTalk: TalkBuilderState() | |
object TalkNameOfGroupTalk: TalkBuilderState() | |
object PairTalk: TalkBuilderState() | |
class TalkBuilder<in S: TalkBuilderState>( | |
var id: Int = 0, | |
var type: TalkType = TalkType.GROUP, | |
var name: String? = null) { | |
companion object { | |
fun create(): TalkBuilder<IdOfTalk> = TalkBuilder() | |
} | |
} | |
@Suppress("UNCHECKED_CAST") | |
fun TalkBuilder<IdOfTalk>.id(id: Int): TalkBuilder<TypeOfTalk> = | |
this.apply { this.id = id } as TalkBuilder<TypeOfTalk> | |
@Suppress("UNCHECKED_CAST") | |
fun TalkBuilder<TypeOfTalk>.pairTalk(): TalkBuilder<PairTalk> = | |
this.apply { this.type = TalkType.PAIR } as TalkBuilder<PairTalk> | |
@Suppress("UNCHECKED_CAST") | |
fun TalkBuilder<TypeOfTalk>.groupTalk(): TalkBuilder<TalkNameOfGroupTalk> = | |
this.apply { this.type = TalkType.GROUP } as TalkBuilder<TalkNameOfGroupTalk> | |
@FunctionalInterface | |
interface UsersToTalk { | |
fun users(vararg users: String): Talk | |
} | |
fun TalkBuilder<TalkNameOfGroupTalk>.name(name: String): UsersToTalk = object : UsersToTalk { | |
override fun users(users: Array<out String>): Talk = | |
Talk(this@name.id, this@name.type, name, listOf(*users)) | |
} | |
fun TalkBuilder<PairTalk>.users(user1: String, user2: String): Talk = | |
Talk(this.id, this.type, null, listOf(user1, user2)) | |
fun TalkBuilder<TalkNameOfGroupTalk>.users(vararg users: String): Talk = | |
Talk(this.id, this.type, this.name, listOf(*users)) |
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
class TalkBuilderTest { | |
@Test fun testGroupTalk() { | |
val groupTalk = TalkBuilder.create() | |
.id(10) | |
.groupTalk() | |
.users("石田三成", "安国寺恵瓊", "小西行長") | |
println(groupTalk) | |
} | |
@Test fun testGroupTalkWithName() { | |
val groupTalk = TalkBuilder.create() | |
.id(10) | |
.groupTalk() | |
.name("西軍チーム") | |
.users("石田三成", "安国寺恵瓊", "小西行長") | |
println(groupTalk) | |
} | |
@Test fun testPairTalk() { | |
val pairTalk = TalkBuilder.create() | |
.id(20) | |
.pairTalk() | |
.users("徳川家康", "小早川秀秋") | |
println(pairTalk) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment