abra-lang
abra-lang copied to clipboard
`as?` operator
For convenience, I'd like there to be an operator which allows inline "unwrapping" of a value as a particular type. For example, let's say there's an enum called Type:
enum Type {
Unit
Fn(returnType: Type, argTypes: Type[])
...
}
An instance of Type could be any one of its variants. To make use of the data contained in the variants, we can use the match expression:
val typ: Type = ...
match typ {
Type.Fn => ...
_ => ...
}
This however, can be a bit cumbersome if you only care about one particular variant. This as? operator would operate on a value and a type T and return an Option<T> which will be present if the value is of type T, and None otherwise. For example
val hasReturn: Bool? = (typ as? Type.Fn)?.returnType == Type.Unit
val hasReturn = ((typ as? Type.Fn)?.returnType != Type.Unit) ?: false