Dotan
Dotan

Reputation: 7622

Scala - implicit conversion of type to Option[type]

This seems very odd to me: say I have a variable which is Option[someType], and I assign a someType object to it, why do I have to explicitly cast my object to an option?

var num: Option[Int] = Option[Int](3) // works
var num: Option[Int] = 3              // seems reasonable, but doesn't compile

Edit: I meant my question to be more about "why did Scala implement it like this", rather than "how to work around this". As you can see I know how to work around it.

What I'm curious about it the rationale that says that an Int can't be thought of as an Option[Int]. I get why an Int isn't a List[Int], for example (allthough I can also imagine a paradigm is which it is) but I don't see the logic in not making the conversion to Option[Int] seamless.

Upvotes: 0

Views: 587

Answers (2)

Tyler
Tyler

Reputation: 18157

An Option can have two different states,

Either it is None:

val num: Option[Int] = None

Or it is defined as Some:

val num: Option[Int] = Some(99)

You could define an implicit conversion to convert from Option[Int] to Int and vice-versa, but doing implicit conversions on types you don't own is generally frowned upon.

The reason your code doesn't compile is because you are assigning a type of Int to something that is expecting Option[Int], and there is no implicit conversion in scope.

Upvotes: -1

Jasper-M
Jasper-M

Reputation: 15086

You don't have to cast it. You simply have to create an object of type Option[Int], because 3 is not an Option[Int].

Option is a type like all others. Would you expect for instance val l: List[Int] = 3 to also work?

If you really want it done automatically you can:

implicit def anyToOption[A](a: A): Option[A] = Option(a)

But implicit conversions from and/or to general types are usually considered bad practice.

Upvotes: 4

Related Questions