Skip to content

Clarification on enums with fields #5229

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

Closed
olafurpg opened this issue Oct 10, 2018 · 2 comments
Closed

Clarification on enums with fields #5229

olafurpg opened this issue Oct 10, 2018 · 2 comments

Comments

@olafurpg
Copy link
Contributor

Related to #5221

One question about enums, https://dotty.epfl.ch/docs/reference/enums/adts.html

enum Option[+T] {
  case Some(x: T)
  case None
}

Is the Option.Some type visible? Is it legal to reference it like this def get(some: Option.Some[Int]) = some.x?

@OlivierBlanvillain
Copy link
Contributor

OlivierBlanvillain commented Oct 12, 2018

As it is currently implemented, yes, this type is visible. It's also possible to explicitly call the constructor to get instances:

scala> enum Option[+T] {
     |   case Some(x: T)
     |   case None
     | }
// defined class Option

scala> new Option.Some(1)
val res0: Option.Some[Int] = Some(1)

But you only get a class (and a type) for cases with fields. Cases without fields become vals:

scala> new Option.None
1 |new Option.None
  |    ^^^^^^^^^^^
  |    type `None` is not a member of Option - did you mean `Option.None`?

scala> type nope = Option.None
1 |type nope = Option.None
  |            ^^^^^^^^^^^
  |       type `None` is not a member of Option - did you mean `Option.None`?

scala> type nope = Option.None.type
// defined alias type nope = Option[Nothing](Option.None)

@olafurpg
Copy link
Contributor Author

Thanks! I just realized this is already addressed in http://dotty.epfl.ch/docs/reference/enums/adts.html

Note that the type of the expressions above is always Option. That is, the implementation case classes are not visible in the result types of their apply methods. This is a subtle difference with respect to normal case classes. The classes making up the cases do exist, and can be unveiled by constructing them directly with a new.

I apologize the noise.

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

2 participants