In Scala you have Option[Int]
which will be Some(number)
or None
and has a property isDefined
which returns true
in the first case and false
in the other.
In C# you have int?
which will be a number
or null
and has a property HasValue
which returns true
in the first case and false
in the other.
Is Scala's Option
the same as a C#'s Nullable type
and are there any differences?
No, it isn't at all the same. In addition to other answers:
Scala has Option[Option[Int]]
; C# doesn't have int??
.
Scala has Option[String]
; C# doesn't have string?
.
In C#, there is an implicit conversion from T
to T?
; in Scala, there is no implicit conversion from T
to Option[T]
(Scala allows you to define such a conversion manually, but this isn't recommended).
This means Option
is a lot more uniform and composable than ?
and allows it to be used much more widely. E.g. Scala's Map[K, V].get(K)
returns Option[V]
; but in .Net, Dictionary<TKey, TValue>[TKey]
can't return TValue?
, because TValue
can be a reference type. Even an equivalent of Option.map
would need to have separate implementations for functions returning value types and reference types.
I'd also like to reiterate that get
should be avoided! isDefined
when not followed by get
is perfectly fine, though.
C#'s Nullable type
is meant to allow value types to have null
values while Scala's Option
is meant to get rid of null
entirely. Instead, you pattern match on Option[A]
to get a Some
or a None
. You can think of Option
as a generalized version of Nullable type
.
However, the problems dealt with aren't exactly the same: C# is trying to add object-like behavior to value types while Scala is trying to provide a safe alternative to null
. However, Scala's Option
does also sort of solve the value type problem Nullable type
was designed for:
scala> case class MyInt(val i: Int) extends AnyVal // scala value type
scala> null : MyInt
<console>:14: error: type mismatch;
found : Null(null)
required: MyInt
null : MyInt
^
scala> None : Option[MyInt]
res1: Option[MyInt] = None
scala> Some(MyInt(1)) : Option[MyInt]
res2: Option[MyInt] = Some(MyInt(1))
I should also mention that Nullable type
is built into the C# language, while Option
is just a regular Scala class in the standard library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With