abra-lang icon indicating copy to clipboard operation
abra-lang copied to clipboard

`as?` operator

Open kengorab opened this issue 3 years ago • 0 comments

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

kengorab avatar Jul 28 '22 02:07 kengorab