Is the Scala parameter the same as the C # Nullable type?

In Scala, you have Option[Int] , which will be Some(number) or None and has an isDefined property that returns true in the first case and false in the other.

In C # do you have an int? which will be a number or null and has a HasValue property that returns true in the first case and false in the other.

Is Scala Option the same as C # Nullable type , and are there any differences?

+5
source share
2 answers

No, this is not 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 #, is there an implicit conversion from T to T? ; Scala does not have an implicit conversion from T to Option[T] (Scala allows you to define such a conversion manually, but this is not recommended).

Does this mean that Option is much more uniform and compound than ? , and allows you to use it much wider. For instance. Scala Map[K, V].get(K) returns Option[V] ; but in .Net, Dictionary<TKey, TValue>[TKey] cannot return TValue? because TValue can be a reference type. Even the equivalent of Option.map must have separate implementations for functions that return value types and reference types.

I would also like to confirm that get should be avoided! isDefined , if you don't follow get , great.

+5
source

C # Nullable type means that value types are null and Scala Option means getting rid of null . Instead, you draw a match on Option[A] to get Some or None . You can think of Option as a generic version of the Nullable type .

However, the problems are not exactly the same: C # is trying to add object type behavior to value types, while Scala is trying to provide a safe alternative to null . However, Scala Option also sorts the Nullable type value type problem, 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)) 

It should also be mentioned that the Nullable type is built into the C # language, and Option is a regular Scala class in the standard library.

+1
source

All Articles