Difference between Option(value) and Some(value)

后端 未结 2 835
没有蜡笔的小新
没有蜡笔的小新 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
    

提交回复
热议问题