LoginSignup
2
2

More than 5 years have passed since last update.

NoneとOption(null)の違いはなんなのか

Posted at

自分の疑問点を整理するためのメモです。

Noneとはなにか?

NoneOption[Nothing]を継承したobjectである。Scalaのコード上でNoneがでてきた場合、それはNoneのシングルトンオブジェクトである(本当か?)。

以下はscala/Option.scalaからの抜粋。Option(null)するとNoneが返る。

  /** An Option factory which creates Some(x) if the argument is not null,
   *  and None if it is null.
   *
   *  @param  x the value
   *  @return   Some(value) if value != null, None if value == null
   */
  def apply[A](x: A): Option[A] = if (x == null) None else Some(x)

Nullとはなにか?

scala.Nothingと同様で全ての型のサブタイプで、型階層の一番下にくる。

nullとはなにか?

nullNullクラスのシングルトンインスタンスである。NullクラスはAnyRefクラスのサブクラスであるので、AnyValのサブクラスであるInt型の変数には代入できない。ひらたく言うとJavaと同じということ。

疑問点

Option[Null] = Noneとはなんなのか?

scala> Option(null)
res67: Option[Null] = None

REPLでOption(null)とするとOption(None)型の値としてNoneが返る、という理解はあっているのかな?

scala> None
res76: None.type = None

scala> None == Option(null)
res77: Boolean = true

NoneOption(null)が等価であるというのはどうやって定義されているんだろう?

参照URL

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2