Difference between Option(value) and Some(value)

后端 未结 2 836
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 09:00

I am new to scala !

My question is, if there is case class that contains a member

myItem:Option[String]

When i construct the class,

相关标签:
2条回答
  • 2021-01-31 09:10

    If you look into Scala's sources you'll notice that Option(x) just evaluates x and returns Some(x) on not-null input, and None on null input.

    I'd use Option(x) when I'm not sure whether x can be null or not, and Some(x) when 100% sure x is not null.

    One more thing to consider is when you want to create an optional value, Some(x) produces more code because you have to explicitly point the value's type:

    val x: Option[String] = Some("asdasd")
    //val x = Option("asdasd") // this is the same and shorter
    
    0 讨论(0)
  • 2021-01-31 09:10

    Option(x) is basically just saying if (x != null) Some(x) else None

    See line 25 of the Source code:

    def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
    
    0 讨论(0)
提交回复
热议问题