user3825558
user3825558

Reputation: 585

How to interpret a val in Scala that is of type Option[T]

I am trying to analyze Scala code written by someone else, and in doing so, I would like to be able to write Unit Tests (that were not written before the code was written, unfortunately). Being a relative Newbie to Scala, especially in the Futures concept area, I am trying to understand the following line of code.

val niceAnalysis:Option[(niceReport) => Future[niceReport]] = None


Update: The above line of code should be:

val niceAnalysis:Option[(NiceReport) => Future[NiceReport]] = None


- Where NiceReport is a case class


-----------Update ends here----------------

Since I am trying to mock up an Actor, I created this new Actor where I introduce my niceAnalysis val as a field. The first problem I see with this "niceAnalysis" thing is that it looks like an anonymous function. How do I "initialize" this val, or to give it an initial value.
My goal is to create a test in my test class, where I am going to pass in this initialized val value into my test actor's receive method.


My naive approach to accomplish this looked like:

val myActorUnderTestRef = TestActorRef(new MyActorUnderTest("None))


Neither does IntelliJ like it. My SBT compile and test fails.

So, I need to understand the "niceAnalyis" declaration first and then understand how to give it an initial value. Please advise.

Upvotes: 0

Views: 138

Answers (1)

Justin Pihony
Justin Pihony

Reputation: 67075

You are correct that this is a value that might contain a function from type niceReport to Future[niceReport]. You can pass an anonymous function or just a function pointer. The easiest to understand might be the pointer, so I will provide that first, but the easiest in longer terms would be the anonymous function most likely, which I will show second:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def strToFuture(x: String) = Future{ x } //merely wrap the string in a future
val foo = Option(strToFuture)

Conversely, the one liner is as follows:

val foo = Option((x:String)=>Future{x})

Upvotes: 2

Related Questions