Skip to content

Instantly share code, notes, and snippets.

@omuomugin
Last active January 23, 2020 13:38
Show Gist options
  • Save omuomugin/bc409d98403b9a558f82f52bdb0ef67f to your computer and use it in GitHub Desktop.
Save omuomugin/bc409d98403b9a558f82f52bdb0ef67f to your computer and use it in GitHub Desktop.
Union
fun unionFun(val a: {Hoge | Fuga | Poyo}) {
// only Hoge, Fuga, Poyo can pass to this function
// still you should cast them using instanceof
// but you know that only Hoge, Fuga and Poyo should be target of instance of
// so you can cover all the types that you want to do something
}
class Hoge:Equatable{
static func ==(lhs: Hoge, rhs: Hoge) -> Bool{
return true
}
}
class Fuga:Equatable{
static func ==(lhs: Fuga, rhs: Fuga) -> Bool{
return true
}
}
class Piyo:Equatable{
static func ==(lhs: Piyo, rhs: Piyo) -> Bool{
return true
}
}
enum Base:Equatable{
case hoge(instance: Hoge)
case fuga(instance: Fuga)
case piyo(instance: Piyo)
static func ==(lhs: Base, rhs: Base) -> Bool{
switch (lhs, rhs) {
case let (.hoge(hl), .hoge(hr)):
return hl == hr
case let (.fuga(fl), .fuga(fr)):
return fl == fr
case let (.piyo(pl), .piyo(pr)):
return pl == pr
default:
return false
}
}
}
// if you want to compare those, you should implement Equtable
let a = Base.hoge(instance: Hoge())
let b = Base.hoge(instance: Hoge())
if(a == b) {
print("if")
} else {
print("else")
}
// you can do something like union type with sealed class
// but it is more strict since sealed class can cover all the target
sealed class Base {
data class Hoge: Base()
data class Fuga: Base()
data class Poyo: Base()
}
val a: Base
when(a) {
is Hoge -> TODO()
is Fuga -> TODO()
is Poyo -> TODO()
}
interface Base {}
class Hoge implements Base {}
class Fuga implements Base {}
class Poyo implements Base {}
// we don't know if there are any other types than Hoge, Fuga and Poyo
// which is implementing Base
// so that we should add else for handling unknown types which implements Base
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment