Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to test the value of an Option?

I often find myself with an Option[T] for some type T and wish to test the value of the option against some value. For example:

val opt = Some("oxbow") if (opt.isDefined && opt.get == "lakes")     //do something 

The following code is equivalent and removes the requirement to test the existence of the value of the option

if (opt.map(_ == "lakes").getOrElse(false))  //do something 

However this seems less readable to me. Other possibilities are:

if (opt.filter(_ == "lakes").isDefined)  if (opt.find(_ == "lakes").isDefined) //uses implicit conversion to Iterable 

But I don't think these clearly express the intent either which would be better as:

if (opt.isDefinedAnd(_ == "lakes")) 

Has anyone got a better way of doing this test?

like image 904
oxbow_lakes Avatar asked Oct 23 '09 07:10

oxbow_lakes


People also ask

How do you find the time value of an option?

Time value is calculated by taking the difference between the option's premium and the intrinsic value, and this means that an option's premium is the sum of the intrinsic value and time value: Time Value = Option Premium - Intrinsic Value.

What is the difference between option premium and intrinsic value?

An option's premium is comprised of intrinsic value and extrinsic value. Intrinsic value is reflective of the actual value of the strike price versus the current market price. Extrinsic value is made up of time until expiration, implied volatility, dividends and interest rate risks.

What is option value finance?

In cost–benefit analysis and social welfare economics, the term option value refers to the value that is placed on private willingness to pay for maintaining or preserving a public asset or service even if there is little or no likelihood of the individual actually ever using it.


1 Answers

How about

if (opt == Some("lakes")) 

This expresses the intent clearly and is straight forward.

like image 50
Walter Chang Avatar answered Oct 04 '22 15:10

Walter Chang