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 7 years ago.
Improve this question
I'm new with Swift 2, I never had developed in Apple. Objective C has seemed ugly and you have to write a lot of code, so Swift liked because the syntax is similar to Java and C and here my question:
In Java you can define a class of this way:
new Thread(){
public run(){
// anything
}
}.start();
Then, Swift can do this? And how?
Thank and greetings
Solution
let myThread=NSThread(target: self, selector: "backgroundWork", object: nil)
myThread.start()
}
func backgroundWork(){
for (self.counter=0;self.counter<10;self.counter++){
//self.myLabel.text = String(self.counter) // Not update UI
self.performSelectorOnMainThread( Selector("updateLabel"), withObject: nil, waitUntilDone: false )
sleep(3)
}
}
func updateLabel(){
self.myLabel.text = String(self.counter)
}
Mostly this syntax (inline definition of anonymous classes) exists because Java doesn't allow the concept of closures or lambda functions, so if you want to pass a function to be invoked you have to pass an instance of a class with the function then declared inline.
In contrast, Swift, like most modern languages has a specific closure syntax which allows you to directly pass executable blocks to another routine, essentially it allows you to treat functions as first class language entities.
So, the bottom line is that no, Swift doesn't allow the construct you've asked about, but it does provide equivalent functionality for the dominant use case. The code most analogous to your example would be:
dispatch_async(...) {
Code to be executed asynchronously here
}
Which is really just syntactic sugar for:
dispatch_async(..., {
Your code here
})
Since the anonymous object is being created only as a holder for a single object, there's really no need for the object, or indeed, the class, and hence the syntax. The only time the Java syntax has a slight advantage is if the callee needs to maintain multiple related callbacks.
Related
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 3 years ago.
Improve this question
I want to understand the feature in java 1.7 which paved the way for lambda expression in Java 1.8. Anonymous function is legacy feature of Java , it exist even before Java 1.7.
Comparator<String> c = new Comparator<String>() {
int compare(String s, String s2) { ... }
};
They are called anonymous classes, not anonymous functions. To find out more about them, your "first stop" should be the Oracle Java Tutorial:
Anonymous Classes
Anonymous classes have existed since Java 1.1. However, it is a stretch to call them "legacy". There are significant differences between anonymous classes and lambdas. For example, an anonymous class may implement multiple methods, and may extend an existing class. By contrast, the innate functionality of a lambda is limited to the code in the lambda itself.
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 7 years ago.
Improve this question
As I know Apache Spark is written in Scala. But its functionality is also exposed as a Java API[1], which in turn can be used in Java programs.
How is this done? Can someone explain me using an example.
In other words if I write a Scala program, and I want to expose it as a java API, what steps should be taken?
[1]http://spark.apache.org/docs/latest/api/java/
It will surely depend on the type of api you are exposing, but in general
Simple methods can be called as is: class A { def doSomething(s: String) } in class A can be called just like a regular java method new A().doSomehing("hello");
Default parameters in methods will not work. You will always have to call the method with the whole parameter list.
traits with behaviour can't be implemented, but if you have common combinations you could create an abstract class and then you can extend that in java. Not sure if this will be solved with default methods for java8 in scala2.12
For object functions you need to call using the escaped path. e.g. object Container { val answer = 42 } you get the constant value from java like int answer = Container$.MODULE$.answer;.
As I said first, it mostly depends on the api you want to expose from scala to java. If you have more specific cases I can edit them in this answer.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Thanks for your objectivity, especially where C# is your language of choice. Angry downvoters, I think I've asked a legitimate question here? Otherwise leave a constructive comment, please.
To the question...
C++ allows passing of (generic) function pointers simply, as follows: How to pass a generic function pointer as parameter
Java uses interfaces for this - also elegant from an OO perspective, we use nothing more than what the basic language already supplies.
However, I have never seen any real advantage to making delegate an explicit concept / keyword, as opposed to just managing the concept of callbacks the way that for example C++ or Java do -- by treating function pointers as just another circumstance under existing type system. (P.S. yes, C# generics are not the same as C++ generics, while Java has runtime rather than compile-time generics, but you get my drift).
(All hubris and dogma aside) Why did the designers of C# see fit to give a new name to a common, existing programming concept that could have been called a generic function pointer / callback? Could delegates not have been more simply represented in C#, without such a concept?
DISCLAIMER I've looked at quite a number of answers on stackoverflow and not one of them has satisfactorily answered why the designers saw fit to include another keyword for something so fundamental as callback handling.
C++ had "official" (non-Boost) "full" delegates from C++11 (std::function)... Before that, getting a pointer to a member function was always a little hackish... So I wouldn't consider C++ to be a good comparison :-) And C++ can overload the round parenthesis, so it is more easy to "hide" the hacks that need to be done and give to the programmer a "simple" way of using the std::function.
Now... Java... To "correct" (but let's say it wasn't an omission, but a calculated decision, so they didn't have anything to correct) the missing delegate concept they first had to introduce anonymous classes in Java 1.1 and then in Java 8 they introduced functional interfaces (as a non-Java programmer, I consider the last thing to be a little hackish... meta-describing that an interface has a single method and then enforcing it at compile time... I don't like it very much...). This because otherwise the boilerplate code that is needed is quite much...
Let's start simple... The IComparer<> interface... It is an interface with a single method, so it is very similar to a delegate...
a simple implementation:
public class MyComparer : IComparer<int>
{
public int Compare(int x, int y)
{
return x.CompareTo(y);
}
}
There is a boilerplate row here, the first one (public class MyComparer : IComparer<int>). By introducing the C# delegate you already gained one row for each use of a delegate... But wait! Let's say that your "delegate" needs a reference to the class that "contains" it...
public class MyComparer : IComparer<int>
{
public MyClass Target;
public int Compare(int x, int y)
{
return Target.Ascending ? x.CompareTo(y) : y.CompareTo(x);
}
}
And now this class needs to be a nested class of MyClass. Note that I don't have anything against nested classes...
We have added a new line (public MyClass Target)... But this code is normally wrong to write... You shouldn't have public non-readonly fields. You could use an auto-property public MyClass Target { get; set; } but that too is synctactic sugar introduced in C# 3.0... without them the boilerplate code would grow... And I would prefer to have a private readonly MyClass Target.. But then I would have to add four lines for the constructor... How many lines do you want me to write for a delegate? :-)
And still C#/.NET delegates give more flexibility: the function you use can have any name, so you can have multiple of them in the same class... The MyComparer could have been implemented as two methods:
public int CompareAscending(int x, int y) {}
and
public int CompareDescending(int x, int y) {}
without adding too much code, or splitting everything in multiple (nested) classes.
Delegates are more than a simple callback. First, it works both for static methods and instance methods and the caller doesn't have to take care of the differences. Second, delegate is not a single method pointer. It can be a "pointer chain", so the caller can call many callbacks with a single call - and again, the caller doesn't have to bother wheter it is a single or multiple call.
Yes, one can implement the same mechanism from scratch - but one can build everything using machine code - what need for high level languages.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
This post may be considered to be inappropriate for stackoverflow, although I'm not trying to insult the Java language or anything like that. I enjoy coding in Java, but there is something regarding System.out.println that I have been wondering for quite a while.
Why is it that we are always forced to type System.out.println() or System.out.print() every time we want to print? Sure, we could make a void function to save time and energy in programs that we will have several print statements (which I sometimes do) like so:
public static void print(String output) {
System.out.print(output);
}
and then just call print (and if you want to really be thorough you can overload the function with arguments involving ints, doubles, chars, etc). But why is it that the Java language itself doesn't already allow us to print to the console by just writing print? Some languages (such as Python) make printing to console that neat and simple - so why doesn't Java?
Again - I'm not saying that the Java language is poorly designed, or trying to start a thread that is intended to bash Java. I'm sure the language designers had their reasons for designing it the way they did, and it would help me to understand why it is so. It would be much easier to just need to type print instead of System.out.print, so there must be reasons for why we must type System.out.print - I just can't figure out those reasons. I've tried googling for information on this issue and can't find anything relevant to the issue.
Please refrain from opinionated responses about the Java language - I want actual facts that explain this phenomenon.
Simply, Java doesn't have global functions.
Also, according to The Java Language Environment (a '90s book co-authored by James Gosling):
Java has no functions. Object-oriented programming supersedes functional and procedural styles. Mixing the two styles just leads to confusion and dilutes the purity of an object-oriented language. Anything you can do with a function you can do just as well by defining a class and creating methods for that class.
It's not to say that functions and procedures are inherently wrong. But given classes and methods, we're now down to only one way to express a given task. By eliminating functions, your job as a programmer is immensely simplified: you work only with classes and their methods.
So there is at least one language designer's reasoning.
You may shorten the call by statically importing System.out:
import static System.out;
class Example {
public static void main(String[] args) {
out.println("hello world!");
}
}
Since System.out is an object, its instance methods cannot be statically imported.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm reading this book, and it's going over static typing, which, after reading the chapter a little bit, I understand as:
Static typing in OOP is defined as explicitly declaring the class an object is an instance of, so that it is predetermined (at compile time, before runtime i.e. Foo var).
The opposite of this is generic programming, where the actual id of the object is yet-to-be-determined (i.e. id var).
Something to keep in mind is that static typing is never necessary (straight from the book), it only improves readability, and eases the debugging process by showing what an object can and cannot do, what it can “see”.
Generic programming, however, is sometimes necessary for things like arrays, where you might need...And this is where I'm confused. Is it actually necessary?
I know that in Java you can enforce the type of objects contained in an array like: ArrayList<Double>, but in Objective-C, and I've done minimal research on this, there is no such method, and therefore, all NSArrays contain ids at compile time.
If this feature (strangely called generics, even though it's static typing and not generic typing), is unavailable in Objective-C, does that mean that generic programming is sometimes necessary?
Yes, generic typing is necessary whenever you need to write something that needs to operate on a number of types without knowing the type at compile time.
While objective-C doesn't contain generics per-se, Ids and void* are basically the same thing. You can write a method that takes in a void* or Id and do some processing on it. Before calling the method, you would do an explicit cast to a void* on the object you want to operate on.
Edit: For instance, what would you do if you wanted to write a method which makes a shallow copy of any typed object? You'd have to do something like copy(void* src,void* dest, int size). There is no way to do this without generics.