0

I found this statement:

var o = None: Option[String]

that you can use to set o to a None, with a view to later maybe setting it to a Some[String]

But how does this actual statement break down syntactically? None is an object that extends Option[Nothing] - but how does the rest of the statement work? For example, what does the colon do?

Many thanks!

user384842
  • 1,946
  • 3
  • 17
  • 24

1 Answers1

5

In scala, you can follow any expression with a type ascription. Like 1: Int is totally valid. So it's really:

var o = (None: Option[String])

The purpose is to tell the compiler that that None should be typed as an Option[String], so that o isn't typed as None.type. Basically, in this example, it's the same as:

var o: Option[String] = None

More here: https://stackoverflow.com/a/2087356/247985

Community
  • 1
  • 1
dhg
  • 52,383
  • 8
  • 123
  • 144
  • Ah fantastic - thank you! Just starting out and trying to get to grips with all the colons and things. This really helps! Thanks again.. – user384842 Feb 13 '15 at 21:25
  • I became a fan of ascriptive typing because of partial functions, where the type really gets verbose. `val x = { case something => } : PF[etc,etc,]`. With function literals you needs parens: `val x = (a => b) : Function1[etc,etc].` – som-snytt Feb 13 '15 at 22:54
  • 1
    In my opinion, a more readable way to write this same assignment is `var o = Option.empty[String]` – Daryl Odnert Feb 13 '15 at 22:55
  • The implementation of that is just `def empty[A] : Option[A] = None`, so it's the same thing, but the reader has to click through or memorize what that method does. IMO it's better to "inline" a method when calling the method would be longer than the method body. – lmm Feb 14 '15 at 19:35