Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

as? operator #355

Open
kengorab opened this issue Jul 28, 2022 · 0 comments
Open

as? operator #355

kengorab opened this issue Jul 28, 2022 · 0 comments

Comments

@kengorab
Copy link
Owner

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant