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.
Related
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.
We know that scala does not support more than 22 params, but if i write this
def echo(args: String*) = for (arg <- args) println(arg)
we can use more than 22 params to call this function like this.
echo("1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1")
But I think this is an array. So, it can do that and i tried this
val a = Array[String]("1","2","3");echo(a)
This code must be wrong, so here's my first question, why is this happening?
and, if i try to write this
echo(a : _*)
It's right,the second question is, what does this sign means '_*'? I can't use this code in other ways like in for(). So, is echo(a : _ *) is a right code?
The echo function is defined to take a variable number of string arguments. This is really only syntactic sugar; the compiler will insert the necessary instructions to wrap the arguments in an array and then pass the array. So the function will actually only receive a single argument at runtime.
The reason you can't pass the array directly is that there is no additional compiler logic to automagically figure out that the string arguments are already wrapped. The function declaration indicates that zero or more strings are expected, the parameter is actually an array, and a compiler error results.
The : _* notation is additional syntactic sugar to account for this problem; by using this syntax you indicate to the compiler that you are intentionally passing an array instead of the variable number of string parameters.
If we have a method:
def hello() = "world"
I'm told that we can call it as:
hello()
also
hello
They both work and will output world, but why?
PS:
I see some words in this https://stackoverflow.com/a/12340289/342235:
No, actually, they are not. Even though they both call a method without parameters, one is a "method with zero parameter lists" while the other is a "method with one empty parameter list"
But I still not understand why hello would work
Scala allows the omission of parentheses on methods of arity-0 (no arguments):
You should only omit the parenthesis when there are no side effects to the invokation though
http://docs.scala-lang.org/style/method-invocation.html
As stated in Oliver Shaw's answer, Scala lets you leave out the parenthesis in functions with 0 arguments. As for why, it's likely to facilitate easy refactoring.
If you have a function that takes no arguments, and produces no side-effects, it's equivalent to an immutable value. If you always call such functions without parentheses, then you're free to change the underlying definition of the function to a value without having to refactor it everywhere it's referenced.
It's worth noting that val definitions are actually modeled as 0-arity methods in scala (unless specified with a private final beforehand).
Scala does something similar with its treatment of arity-1 functions defined on classes. You are allowed to omit the dot and the parenthesis. For example:
case class Foo(value: String) {
def prepend(value2: String) = Foo(value2 + value)
}
Foo("one").prepend("two")
// is the same as...
Foo("one") prepend "two"
This is because Scala models all operators as arity-1 functions. You can rewrite 1 + 2 as 1.+(2) and have it mean the same thing. Representing operators as fully-fledged functions has some nice qualities. You can expect to pass an operator anywhere that you could pass a function, and the definition of the operator is actually defined for class instances (as opposed to a language like C#, where the infix operators are actually static methods that use special syntactic sugar to let them be represented as infix).
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.