How do closures work in Java 7? [duplicate] - java

This question already has answers here:
Closure in Java 7 [closed]
(7 answers)
Closed 9 years ago.
I haven't worked with closures in java 7 as yet and was wondering how they work and what is their main advantage or best use case in utilizing them?
Update:
I should have done my homework better. Here is the Project Lambda site for JSR 335 : Lambda Expressions for the Java Programming Language. They are claiming clousures will be in Java 8. I'll have to look into it more to see if that is really the case.

Java 7 has no closures. They've been rumored for a long time, and they are apparently set to appear in Java 8. Of course, I have been promised a Ghostbusters reboot that has been rumored too.
However, you can fake closures with anonymous inner classes. But make no mistake, these aren't closures.
As for the benefits of closures, I can't put it any better than Stack Overflow legend #jaif from this post:
"You can see it as a generalization of a class.
Your class holds some state. It has some member variables that its methods can use.
A closure is simply a more convenient way to give a function access to local state.
Rather than having to create a class which knows about the local variable you want the function to use, you can simply define the function on the spot, and it can implicitly access every variable that is currently visible.
When you define a member method in a traditional OOP language, its closure is "all the members visible in this class".
Languages with "proper" closure support simply generalize this, so a function's closure is "all the variables visible here". If "here" is a class, then you have a traditional class method.
If "here" is inside another function, then you have what functional programmers think of as a closure. Your function can now access anything that was visible in the parent function.
So it's just a generalization, removing the silly restriction that "functions can only be defined inside classes", but keeping the idea that "functions can see whatever variables are visible at the point where they're declared". "

Related

google support for kotlin in android development [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
As we now Google announced in 2017 first-class support for Kotlin.
But what does it change? Is there more documentation for new features written in Kotlin language?
How does it affect Java?
My another question:
Are Kotlin written aps generally faster?(on Android device)
EDIT: Guys I though this question is properly asked.. Don't vote me down
Java Issues Addressed by Kotlin
NullSafety — The Billion Dollar Mistake is the name given to the danger of null references in code. Kotlin’s type system is aimed at eliminating the danger of these null references. This has been one of the most common pitfalls in Java — and many other programming languages as well.
No more Raw Types — Kotlin is designed with Java interoperability in mind. So now, existing Java code can be called from Kotlin in an effective way. This allows the calling of Java code from Kotlin. Alternatively, Kotlin code can be used in Java rather smoothly.
Invariant Arrays — The basic types used in Kotlin are Numbers, Arrays, Characters, and Strings. Unlike Java, the arrays in this programming language are invariant, meaning that Kotlin does not let a user assign an Array to an Array. This prevents a possible Run time Failure, which is one of the issues faced in Java.
Function Types — In Kotlin, a lambda expression or an anonymous function can access the variables declared in the outer scope. That is opposed to Java’s SAM-conversions — Kotlin has proper function types.
Use-site Variance — Wildcard Types are one of the trickiest parts of Java’s Type System. This issue does not occur in Kotlin — as it does not have any Wildcard Types, just Type Projections and declaration-site variances.
Exceptions — Kotlin does not have any checked exceptions, as all exception classes in this language are the descendants of the class Throwable. And every exception has a message, stack trace, and an optional cause.
Why Choose Kotlin
Smart Casts
Working with the mixed types requires knowing the type of an object at the Run time in order to safely cast the object to the desired type — and, further, to call methods or access properties on it. For class casting in Java, we first check the type of the variable using the ‘instance of’ operator and then cast it to the target type.
Whereas in Kotlin, when we perform an ‘!is’ or ‘is’ check on a variable, the compiler tracks this information and will automatically cast the variable to the target type where is the ‘!is’ or ‘is’ check is true in the scope.
Singletons
Once in a while, a user needs to create an object of a slight modification of some class but without explicitly declaring a new subclass for it. Java handles this case with anonymous inner classes, but Kotlin generalizes the same concept by using object expressions and declarations. Just like the anonymous inner classes in Java, the code in object expressions can access variables from the enclosing scope. But in Kotlin, this is not restricted to final variables like in Java.
Data Classes
The whole purpose of creating classes is to hold data and in some classes — standard functionality with utility functions can be mechanically derived from that data. This is known as a Data Class in Kotlin. These classes generally contain some old boilerplate code in the form of toString(), hashcode(), equals(), setters, and getters.
Basically, Kotlin’s Data Classes are like regular classes but with some additional functionality.
NOTE: There are more things that have in Kotlin which help developers to write faster, consize and clean code

Is there any runtime benefit of using lambda expression in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am reading couple of blogs and answers as well on lambda expression provided in Java 8.
I am not able to figure out, is there any run-time benefit of unit lambda expression or not?
I have copied following text from different sources which are too much confusing to me.
One answer is saying -
"lambdas do NOT create a new scope, they share the same scope as the
enclosing block/environment"
In the one blog -
"There are no runtime benefits of using lambda expressions, so I will
use it cautiously because I don’t mind writing few extra lines of
code."
From one other blog -
"one more benefit lambda expressions Sequential and Parallel Execution
Support by passing behavior in methods"
So there is lots off confusion for me.
Please help me to clear this so I can avoid keeping wrong approach in mind before digging more in to this stuff.
I have run following code and I can say the lambda expression in the following code is just replacement for the anonymous inner class and its running on main thread.
List<Integer> list = new ArrayList<>();
list.add(12);
list.forEach(V -> {
System.out.println(V);
});
Are we reducing any time complexity or space complexity?
“lambdas do NOT create a new scope, they share the same scope as the enclosing block/ environment” is an almost correct statement (they do create a new scope, but not the way inner classes do), but doesn’t have anything to do with runtime performance. This has to do with correctness of the code.
Within an anonymous inner class, identifiers may get resolved through the lexical scope, finding a match in the surrounding scope, or by inheritance, finding a match in the class hierarchy of the anonymous inner class. The rules for resolving identifiers in this scenario are complex and easy to confuse.
Further, the body of an anonymous class creates a new scope that allows to create variables having the same name as local variables of the surrounding context, shadowing these variables.
In contrast, a lambda expression works like other expressions within the context they are written in. They do not inherit any members from the functional interface they will get converted to, they can not create new variables shadowing existing local variables and even this and super have the same meaning as within the surrounding context:
JLS§15.27.2. Lambda Body
Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).
So when you have the expressions x.foo(y) and () -> x.foo(y) within the same block, it will be obvious whether x and y will be the same x and y for both expressions and hence, it will be the same foo method in each case, which you can not say that simple for anonymous inner classes, as you have to analyze the entire inner class and its type hierarchy first.
This makes lambda expressions ideal for scenarios where you want to define a local function and, e.g. pass it to a method as a parameter, without even thinking about the actual interface being used. The interface itself does not influence the lambda expression beyond defining the functional signature.
But this also implies that there might be use cases of anonymous classes that can’t be covered by lambda expressions. But the purpose of lambda expressions isn’t to be a general replacement for anonymous inner classes.
When it comes to performance or easy of parallel processing, shmosel’s answer says it already. We can’t make such general statements without knowing which operation/problem we are looking at and which solutions we are actually comparing.
lambdas do NOT create a new scope, they share the same scope as the enclosing block/environment
I'm not sure what your point is with this quote.
There are no runtime benefits of using lambda expressions
Relative to what? Lambdas may perform better than anonymous classes, but neither will outperform simple control flow statements.
one more benefit lambda expressions Sequential and Parallel Execution Support by passing behavior in methods
Streams and lambdas enable declarative programming, which makes parallelization more accessible. So using lambdas may indirectly improve performance.
anonymous inner class is compiled into extra .class file, but lambda is translated dynamically. Here is a detailed post: How will Java lambda functions be compiled?

Do `public/protected/private` keywords have any effect on performance? [duplicate]

This question already has answers here:
How does access modifier impact the performance in Java?
(2 answers)
Closed 6 years ago.
As far as I know, public/protected/private keywords have no effect on creation time. But I wonder that keeping a public object/class accessible should have a cost. Does it have a cost?
No they don't. They are essentially compile-time constructs.
That said, some OOP languages (e.g. C++) can make optimisation decisions based on something being private. But that's unlikely to be exploitable in Java due to reflection, since in Java, being private doesn't guarantee its invisibility to things outside the class.
keeping a public object/class accessible should have a cost.
Yes, the compiler needs to check whether the thing you're accessing is private, protected and public. It then decides whether you're allowed to access it.
But at runtime, the runtime doesn't need to check whether you are allowed to access the variable. Why? Because for a program to run, it must be compiled (unless you're using an interpreted language like JS). If you try to access a variable that you're not allowed to, it won't even run!
So at runtime, the runtime doesn't need to worry about whether you can access the variable, and hence, there's no effect on performance.

default method in interface with difination [duplicate]

This question already has answers here:
What is the "default" implementation of method defined in an Interface?
(3 answers)
Closed 6 years ago.
I was studying lambada and there was a point which states that in java 8 we can declare a method with definition in interfaces like
interface Test {
default String method(){
return "string";
}
}
and as per specification we can use two methods with same signature but depends on programmer how he wants to use it?
Now the question is same task can be if achieved by using definition not declaration then what's the point of using default method?
like they behave same as regular method definition and programmer need to declare body and rest part?
what is the actual point as it seems a bit hard to grasp
thanks #ElliottFrisch and #kagemusha for hint after searching i got the answer
Why default methods?
List<?> list = …
list.forEach(…); // lambda code goes here
The forEach isn’t declared by java.util.List nor the java.util.Collection interface yet. One obvious solution would be to just add the new method to the existing interface and provide the implementation where required in the JDK. However, once published, it is impossible to add methods to an interface without breaking the existing implementation.
So it’d be really frustrating if we have lambdas in Java 8 but couldn’t use those with the standard collections library since backwards compatibility can’t be sacrificed.
Due to the problem described above a new concept was introduced. Virtual extension methods, or, as they are often called, defender methods, can now be added to interfaces providing a default implementation of the declared behavior.
Simply speaking, interfaces in Java can now implement methods. The benefit that default methods bring is that now it’s possible to add a new default method to the interface and it doesn’t break the implementations.
It doesn’t seem to be the language feature that would be appropriate to use every day, but it seems to be essential for Java Collections API update to be able to use lambdas naturally.

Java: place of constructors, static methods, public methods, private? [duplicate]

This question already has answers here:
Are there any Java method ordering conventions? [closed]
(8 answers)
Closed 7 years ago.
I have come to the question: what is the most preferred way of placing methods? I mean, should first declare static methods, then constructors, then public methods, then protected, then private, etc? Is there some kind of convention, like I guess everyone places fields (instance variables) on top of the code. Is there the same policy about methods?
I guess it depends on the language you use. What about Java?
This is somewhat opinion based, but the Google Java Style doc puts it nicely:
The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.
What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering.
https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s3.4.2-class-member-ordering
Most of the code I see in the open source world uses some variation of
static fields
instance fields
constructors
methods (instance and static)
anonymous classes
It comes down to team preference, but it is always good to follow convention
Talking about execution, JVM guarantees the order which we cannot change.manage.
But from code readability point of view , YES ordering does looks good. Following coding standards is what should do.
Static fields -> instance fields/variables
As we know, Static Block is always called once class is loaded, so we should have it.
Then constructors, for object creation, there is no point of writing constructor at the end.
also a good read here as suggested above.

Categories

Resources