In Scala, does AnyRef.clone perform a shallow or deep copy?
Short answer: shallow.
Not-so-short answer:
Unless it's overridden, AnyRef.clone() uses the Java's Object.clone() as its implementation.
Javadoc on Object.clone():
The method clone for class Object
performs a specific cloning operation.
First, if the class of this object
does not implement the interface
Cloneable, then a
CloneNotSupportedException is thrown.
Note that all arrays are considered to
implement the interface Cloneable.
Otherwise, this method creates a new
instance of the class of this object
and initializes all its fields with
exactly the contents of the
corresponding fields of this object,
as if by assignment; the contents of
the fields are not themselves cloned.
Thus, this method performs a "shallow
copy" of this object, not a "deep
copy" operation.
Please note:
AnyRef.clone(), like its counterpart in Java, has a "protected" access level, so its not callable from everywhere.
You will need to implement Cloneable in order for clone() to work.
Long answer: Read Effective Java, 2nd Edition, Item 11: Override clone judiciously
Summary: Don't use it. There are better alternatives.
Related
I try to understand what's the data type of scala.concurrent.Future?
I found the following types from the scala lang documentation, but still unsure the differences between them, and when to use which one?
trait Future[+T] extends Awaitable[T] //for concurrent programming
object Future extends AnyRef //not sure?
http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future.html
http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future$.html
Sorry, but I got an impression that you need first to get some scala basis, what is trait, what is companion object, and other stuff.
Back to your question.
When you want to execute something concurrently, you can wrap it in Future. Your code has some output type (SomeType, could be Unit - equivalent of void), after wrapping into Future you will get Future[SomeType] - it is extension of trait Future[+T]. Than you need some execution context (thread pool) to execute your Future.
Try to find and read "Programming in Scala" written by Martin Odersky, Lex Spoon and Bill Venners, very good for beginners.
Like a collection (List, Array, etc.), a Future is a type that works on/with another type. A useful comparison is the Option type.
Just as an Option[Int] might be an Int value (and it might not), a Future[Int] might not be an Int value yet. It could be that the Int value is still being calculated, or being extracted from a database table, or being retrieved from a distant network location. Whatever the cause, if it's a slow process there's no reason to wait for it. Turn it into a Future[Int] so that your program can go on with other important tasks.
As for the object Future, that is a singleton object that has a handful of methods for handling/manipulating existing Future elements. Future.sequence() is a useful example.
It is unclear whether you are talking about the trait Future or the singleton object Future. I will answer both.
The trait doesn't have a type. It is a type.
All singleton objects foo have the singleton type foo.type, so the singleton object Future has the singleton type Future.type.
In Scala, object is a singleton class, which means, that there only exists a single instance during the runtime of the application. There are several ways to implement singletons in most languages, but most often, you risk some issues such as thread safety. Scala's object takes care of the implementation of this pattern for you.
A common pattern in Scala is creating an object that has the same name as a class, like the one in your example. This is called a companion object. A common use for these is for essentially defining the equivalents of static methods from Java. You can declare methods that are common for all instances, or methods that handle and manipulate instances of the class. In Java, for example, you would declare them as static in the body of the class itself. The companion object helps you with separation of concern in this case.
In c# we have the protected accessor which allows class members to be visible on inherited clases but not for the rest.
In Swift this doesn't exist so I wonder what's a correct approach for something like this:
I want to have a variable (internal behavior) and and a public method using this variable on a base class. This variable will be used also on inherited clases.
Options I see
Forget about base class and implement variable and methods everywhere I need it. WRONG, duplicated code
Implement inheritance by composition. I'd create a class containing common methods and this will be used by composition instead of inheritance. LESS WRONG but still repeating code that could be avoided with inheritance
Implement inheritance and make variable internal on base class. WRONG since exposes things without any justification except allowing visibility on inherited clases.
Implementation Details for Base Class
I want to have a NSOperationQueue instance and and a public method to cancel queued operations. I add new operations to this queue from inherited classes.
In Swift the correct answer is almost always protocols and extensions. It is almost never inheritance. Sometimes Cocoa stands in our way, because there are classes in Cocoa more often than protocols, but the goal is almost always protocols and extensions. Subclassing is our last choice.
Your particular case is confusing because NSOperationQueue already has a public method to cancel queued operations (cancelAllOperations). If you want to protect the queue from outside access (prevent callers from using addOperation directly for instance), then you should put the queue inside another type (i.e. composition), and forward what you want to the queue. More details on the specific problem you're solving would allow us to help suggest other Swift-like solutions.
If in the end you need something that looks like protected or friend, the correct solution is private. Put your subclass or your friend in the same file with the target, and mark the private thing private. Alternately, put the things that need to work together in a framework, and mark the attribute internal. The Swift Blog provides a good explanation of why this is an intentional choice.
According to Platform::Object Class docs ( http://msdn.microsoft.com/en-us/library/windows/apps/hh748265.aspx ) there is a method to create a shallow copy:
[MemberwiseClone] method
Creates a shallow copy of the current Object.
How to use it ? I have tried object->MemberwiseClone(), Object::MemberiwseClone(), without success ?
thanks
There is no such member function; the documentation is incorrect. If you want to make one of your types copyable, you can implement a constructor that makes a copy or a member function that returns a copy.
(I'll inform the appropriate people so that the documentation is corrected.)
I've written a Scala trait, named Cache[A,B], to provide a caching API. The Cache has the following methods, asyncGet(), asyncPut(), asyncPutIfAbsent(), asyncRemove().
I'm going to have a few static methods, such as getOrElseUpdate(key: A)(op: => B). I don't want methods like this as abstract defs in the Cache trait because I don't want each Cache implementation to have to provide an implementation for it, when it can be written once using the async*() methods.
In looking at Google Guava and parts of the Java library, they place public static functions in a class that is the plural of the interface name, so "Caches" would be the name I would use.
I like this naming scheme actually, even though I could use a Cache companion object. In looking at much of my code, many of my companion objects contain private val's or def's, so users of my API then need to look through the companion object to see what they can use from there, or anything for that matter.
By having a object named "Caches" is consistent with Java and also makes it clear that there's only public functions in there. I'm leaning towards using "object Caches" instead of "object Cache".
So what do people think?
Scala's traits are not just a different name for Java's interfaces. They may have concrete (implemented) members, both values (val and var) and methods. So if there's a unified / generalized / shared implementation of a method, it can be placed in a trait and need not be replicated or factored into a separate class.
I think the mistake starts with "going to have a few static methods". Why have static methods? If you explain why you need static methods, it will help figure out what the design should be.
Similar question but not quite the same thing
I was thinking that with extension methods in the same namespace as the interface you could get a similar effect to multiple inheritance in that you don't need to have duplicate code implementing the same interface the same way in 10 different classes.
What are some of the downsides of doing this? I think the pros are pretty obvious, it's the cons that usually come back to bite you later on.
One of the cons I see is that the extension methods can't be virtual, so you need to be sure that you actually do want them implemented the same way for every instance.
The problem that I see with building interface capability via extension methods is that you are no longer actually implementing the interface and so can't use the object as the interface type.
Say I have a method that takes an object of type IBar. If I implement the IBar interface on class Foo via extension methods, then Foo doesn't derive from IBar and can't be used interchangeably with it (Liskov Substitution principle). Sure, I get the behavior that I want added to Foo, but I lose the most important aspect of creating interfaces in the first place -- being able to define an abstract contract that can be implemented in a variety of ways by various classes so that dependent classes need not know about concrete implementations.
If I needed multiple inheritance (and so far I've lived without it) badly enough, I think I'd use composition instead to minimize the amount of code duplication.
A decent way to think about this is that instance methods are something done by the object, while extension methods are something done to the object. I am fairly certain the Framework Design Guidelines say you should implement an instance method whenever possible.
An interface declares "I care about using this functionality, but not how it is accomplished." That leaves implementers the freedom to choose the how. It decouples the intent, a public API, from the mechanism, a class with concrete code.
As this is the main benefit of interfaces, implementing them entirely as extension methods seems to defeat their purpose. Even IEnumerable<T> has an instance method.
Edit: Also, objects are meant to act on the data they contain. Extension methods can only see an object's public API (as they are just static methods); you would have to expose all of an object's state to make it work (an OO no-no).