am new into scala and have a basic question. How do I access a variable from outside the scope of an object in scala? Need help on this issue.
When I tried to print the value of variable it gave below error:
error: not found: value x
Below is the code block. I need an user i/p and need to access that outside the scope of method in scala. Please help.
def main(args: Array[String]) {
val x:Int = args(0).toInt
}
println("Input : " + main _)
val a = main(x)
println(a)
In scala, you cannot access to the variables outside the scope. If you need them in other scope:
You might define a global variable and access it somewhere else. (not recommended as this is not a best practice in functional languages set aside scala.)
You might create a function that creates the output you need, and call that function when you need.
In your example, you tried to call main with parameter x, but it is undefined in that scope. Also, main does not return anything (returns Unit which is similar to void in Java), so your println function would not display anything even if you could access to x.
Related
I am studying Martin Odersky's Principles of Reactive Programming. When talking about the implementation of a simple FRP framework, he at the beginning gave one that uses StackableVariable(i.e. DynamicVairable) to keep track of the currently updated signal, which I can understand. But at the end of the slides, he mentioned that a cleaner solution is to use implicit parameter instead of DynamicVariable. Could anyone please show me how this can be done?
The link to the slides didn't work for me. As I tried googling it, I now use 1 as reference.
The dynamic variable is a thread-local variable that holds the state of what Signal is currently evaluated. This is needed so that the apply method of Signal can access this information. Let's consider the following example code:
val a: Signal[Int] = ???
val b: Signal[Int] = ???
val xPlusY: Signal[Int] = Signal(a() + b())
Here, when a() is called, it adds itself to the list of dependencies to the currently evaluating Signal. As this information is not accessible anywhere else, we basically use a thread-local a.k.a. global variable.
This solution has a few problems. For example, we can also call a() if we're not inside any Signal(). Also, well, we have to use a global variable.
The solution would be to give this information to a() via an implicit argument: We change the signature from
Signal[T]#apply(): T
to
Signal[T]#apply()(implicit triggeredBy: Signal[_])
(Note that we'd probably want to use some new type TriggeredBy that encapsulates a Signal instead)
This way, the implementation of this method will have access to its originating Signal without a global/thread-local variable.
But now we have to supply this implicit somehow. One option is to also change the signature of the Signal-creation function from
def Signal.apply[T](fun: => T): Signal[T]
to
def Signal.apply[T](fun: Signal[_] => T): Signal[T]
Unfortunately, the syntax of our example code has to change then, because we have to supply a function instead of a body:
val xPlusY: Signal[Int] = Signal { implicit triggeredBy => a() + b() }
There are a few solutions to this problem:
Wait until implicit function types will have been implemented 2. This probably won't happen anytime soon, but it will allow us to write the Signal.apply signature as follows:
def Signal.apply[T](fun: implicit Signal[_] => T): Signal[T]
and then be able to write Signal(a() + b()) again.
Use some macro magic to transform code of the form Signal(a() + b()) to Signal.internalApply(implicit triggeredBy => a() + b()) code. This means, that Signal.apply is now a macro. This is the road that scala.rx3 has gone and it works well from a usage point of view. This also allows us to write Signal(a() + b()) again.
Update: updated link to implicit functions explanation to a more detailed blog artikle
When I read book I saw the following is a function:
val plusOne=(x:Int)=>x+1
well, when the function invoke a variable it becomes a closure:
The following is a closure:
val count=1
val plusOne=(x:Int)=>x+count
Is that right - If a function used any variable, then it will become closure?
No, that's not right.
What you are seeing there, is just a nested function. The defining feature of a closure is that it closes over its enclosing lexical environment, and thus extends the lifetime of the variables in that enclosing environment beyond the lifetime of that enclosing environment.
See this for an example:
def makeAdder(inc: Int) = (x: Int) => x + inc
val threeAdder = makeAdder(3)
threeAdder(20) //=> 23
threeAdder(39) //=> 42
Even though the method makeAdder has exited and thus the local variable inc has gone out of scope, the closure returned by makeAdder still has access to it, because it closes over the lexical environment of makeAdder. So, a nested function with free variables becomes a closure as soon as its enclosing lexical scope ends and it escapes from it.
Yes, that is right.
You can read more about it on TutorialsPoint: Scala closures.
This definition of a closure is not specific to scala.
I think yout Code is wrong.
If count is var.. like..
var count = 1
Then the function value of plusOne is created and closed at runtime, so we can call it closure.
But in your example count is val type. so the function value is always closed at compile time.. so it's not closure.
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.
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})
I've been working on learning the ins and outs of scala, and recently I've come across something I'm curious about.
As I understand, if I want to pass a block of code that is effectively lazily evaluated to a function, (without evaluating it on the spot) I could type:
def run(a: =>Int):Int = {...}
In this sense, the function run receives a block of code, that is yet to be evaluated, which it evaluates and returns the computed Int of. I then tried to extend this idea to the List data structure. Typing:
def run(a: List[=>Int]) = {...}
This however, returns an error. I was wondering why this is disallowed. How, other than by this syntax can I pass a list of unevaluated blocks of code?
=>Int is the syntax for by name parameters. =>Int is not a type, so it can't be used as a parameter to List. However, ()=>Int is a type. It's the type of nullary functions that return Int. So this works:
def run(a: List[()=>Int]) = {...}
by-name parameter is not a first-class type in Scala.
List[()=>Int] is one of the solution. otherwise, You can use following Lazy data structure.
https://gist.github.com/1164885
https://github.com/scalaz/scalaz/blob/v6.0.4/core/src/main/scala/scalaz/Name.scala#L99-107
https://github.com/scalaz/scalaz/blob/v7.0.0-M7/core/src/main/scala/scalaz/Name.scala#L37-L60
https://github.com/scala/scala/blob/v2.10.0/src/reflect/scala/reflect/internal/transform/Transforms.scala#L9-23
https://github.com/harrah/xsbt/blob/v0.12.1/compile/api/SafeLazy.scala
https://github.com/okomok/ken/blob/0.1.0/src/main/scala/com/github/okomok/ken/Lazy.scala
https://github.com/playframework/Play20/blob/2.1-RC1/framework/src/play/src/main/scala/play/api/libs/functional/Util.scala#L3-L11
In scala it is possible to define a local block in a function. The local block evaluates to the last statements, for example,
val x = {val x =1;x+1}
Here x==2, the inner val x is local to that block.
However those local blocks can cause sneaky bugs when writing anonymous classes. For example (from scala's reference)
new Iterator[Int]
{...} // new anonymous class inheriting from Iterator[Int]
new Iterator[Int]
{...} //new Iterator[Int] followed by a "dangling" local block
Differntiating between the two cases is frustrating.
Sometimes those two code snippets can compile, for instance if instead of Iterator[Int], Range(0,1,1) is used.
I thought about it and couldn't find a case where "dangling" local block (ie, a local block whose value isn't use) is needed (or makes the code more elegant).
Is there a case where we want a local block, without using its value (and without putting it in a different function and calling this function)? I'll be glad for an example.
If not, I think it would be nice to issue a warning (or even forbid altogther) whenever scalac encounter "dangling" local block. Am I missing something?
Why not write
new Iterator[Int] {
...
}
Edit:
This is the style used by Programming in Scala (see sample chapter pdf)
new RationalTrait {
val numerArg = 1 * x
val denomArg = 2 * x
}
and Java Coding Conventions.
Open brace "{" appears at the end of the same line as the declaration statement
{
import my.crazy.implicit.functions._
// use them...
}
// code I know isn't touched by them.