开发者

Scala Option vs Java null [duplicate]

开发者 https://www.devze.com 2023-03-18 02:49 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Why Option[T] ? I am a newbie on Scala and I can\'t really feel that sensation of that difference between n
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why Option[T] ?

I am a newbie on Scala and I can't really feel that sensation of that difference between null on java and Option on Scala . I know that none is an object and if I write smth like that on Scala , it will go safe :

val map = Map("koko" -> "is a cat")
val string:Option[String] =map.get("other")
println(string.map(a=>println(a.toString)) )

I well get None as a result instead of throwing an exception . It's interesting .

However if I need the returning value not to be wrapped by Some . I will use .get to return the value .

In our example , it will throw an exceoption:

map.get("other").get.map(a=>println(a.toString))

I know I can handle this issue by using "match" . I am taking here that I need to learn what's that booming on option on Scala vs null on java !

What I still couldn't get is that how could开发者_开发知识库 I use the advantages of Option but in case there are values existed into my variable , return the value not Some(value)

def testOption(): String = {
  val map = Map("koko" -> "is a cat")
  val string: Option[String] = map.get("koko")
  string
}

I mean is there any way to make this code works instead of updating the return value to be Option[String] ! Imagine that I have to return a String in order to be set into my bean variable that is of type String not Option[String]

How could I make that works without any kind of match !! I guess if there smth that makes it works , that will make me understand well the power of Option.


Options are actually quite useful. In Java, it's tough to document whether or not something can be null. In Scala, you can often assume all variables are not null.

This gets really useful when you have some computation that can fail or may not be defined. A good instance would be if you have a webapp and there's some user data that isn't filled out, so the computation can't run. If you had the user data in a map, you could do something like

val myData = map.get(userId).map(doFunction).map(toHtml)
println(myData.getOrElse(noDataHtml))

So clearly here we never have to worry about null. If the user data is in the map, we proceed with the computation and then turn that into html. Otherwise, we'll just print out a default html. In Java, at each stage we'd have to do a null check, but in Scala we can just chain functions.

0

精彩评论

暂无评论...
验证码 换一张
取 消