Last active
January 2, 2016 16:18
-
-
Save jasononeil/8328885 to your computer and use it in GitHub Desktop.
`AcceptEither`, a way to accept either one type or another, without resorting to "Dynamic", and still have the compiler type-check everything and make sure you correctly handle every situation.
This file contains hidden or 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 Test { | |
static function main(){ | |
stringOrInt( "hello" ); | |
stringOrInt( 10 ); | |
} | |
static function stringOrInt( either:AcceptEither<String,Int> ) { | |
switch either.type { | |
case Left(str): trace("string: "+str); | |
case Right(int): trace("int: "+int); | |
} | |
} | |
} | |
abstract AcceptEither<A,B> (Either<A,B>) { | |
public inline function new( e:Either<A,B> ) this = e; | |
public var value(get,never):Dynamic; | |
public var type(get,never):Either<A,B>; | |
inline function get_value() switch this { case Left(v) | Right(v): return v; } | |
@:to inline function get_type() return this; | |
@:from static function fromA( v:A ):AcceptEither<A,B> return new AcceptEither( Left(v) ); | |
@:from static function fromB( v:B ):AcceptEither<A,B> return new AcceptEither( Right(v) ); | |
} | |
enum Either<A,B> { | |
Left( v:A ); | |
Right( v:B ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment