Private setter for property using concise syntax [duplicate] - kotlin

This question already has answers here:
In kotlin, how to make the setter of properties in primary constructor private?
(2 answers)
Closed 3 years ago.
class kotlass(var propOne:String, var propTwo:String) {...}
So this is the concise way of declaring properties in Kotlin. I want to change setters (default implementation) to private. Is this possible without giving away the concise syntax?

You can use the val keyword instead of var. val stands for value, and means the property will be immutable and only a getter will be generated (var stants for variable and generates both a getter and a setter).
See also the official reference:
Much the same way as regular properties, the properties declared in the primary constructor can be mutable (var) or read-only (val).
This doesn't strictly "change the setter to private". It actually causes the property to be immutable. If you want the variable to be mutable internally, then no, there is no way to do that using only the default constructor. You would have to use methods described in Kotlin : Public get private set var.

Related

When is a backing field generated in Kotlin?

Quoting Kotlin documentation on 'Backing properties'.
A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.
For example, there would be no backing field in the following case:
val isEmpty: Boolean
get() = this.size == 0
At least one of the accessors (setter) is using the default implementation, then why would there be no backing field in the above case?
At least one of the accessors (setter) is using the default implementation
The example property is a val, so there is no setter. The only accessor is the getter, and that one doesn't use the default implementation, so no backing field.
I agree it would have been clearer if they started with a var example, but this example is definitely worth noting to clarify how it works for vals.

Java: How does automatic casting work? [duplicate]

This question already has answers here:
Why do I get a compile-time error when calling a subclass method using superclass reference?
(6 answers)
Closed 4 years ago.
From a book:
What if you want to call a method that’s defined by a subclass from an object
that’s referenced by a variable of the superclass? Suppose that the SoftBall class
has a method named riseBall that isn’t defined by the Ball class. How can you
call it from a Ball variable? One way to do that is to create a variable of the sub-class and then use an assignment statement to cast the object:"
Ball b = new SoftBall();
SoftBall s = (SoftBall)b;
// cast the Ball to a SoftBall
s.riseBall();
I don't understand this. Why can't I just directly call the method from the variable b? (The variable b in this case holds a Softball object). Why the casting?
How can you call it from a Ball variable?
You can't. The compiler doesn't know that this Ball is a SoftBall as opposed to a BaseBall.
You have to cast explicitly. This is merely a way of saying to the compiler: "I know more about the type of this instance than you". The compiler trusts you (mostly: it wouldn't let you cast it to, say, a String), and lets you deal with the consequences (e.g. a potential ClassCastException)

Naming of formal parameters in setters with synthesized properties [duplicate]

This question already has answers here:
Good practice for disambiguating argument names versus instance variable names in Objective-C
(3 answers)
Closed 9 years ago.
I have been learning and using Objective-C for quite some time now (it also kind of was my first OOP language) and I finally would like to know how to correctly name synthesized properties.
Let's take the following scenario:
I have got a property called someVariable.
#property (nonatomic, retain) NSString *someVariable;
and synthesize it
#synthesize someVariable;
How would the custom setter look like conventionally ?
1)
I would go ahead and say something like
-(void)setSomeVariable:(NSString *)someVar{
//input parameter MAY sound/look foreign due to the difference to the property
someVariable = someVar;
}
2) (illegal)
But I would like to name the formal parameter just like the property for the sake of readability and convenience. More like in Java like this:
-(void)setSomeVariable:(NSString *)someVariable{
//obviously illegal because this would call the setter over and over again
self.someVariable = someVariable;
}
3) (unconventional)
and according to what I have been reading in the past this
#synthesize someVariable = _someVariable;
is said to be unconventional and not supposed to be used.
So, am I correct in concluding that the way I have been doing it until now, is the only way to create a custom setter ?
3) is not unconventional, it's exactly what the compiler does if you don't provide the #synthesize statement.
This means that, without the #synthesize statement and the ivar declaration, you have an implicit ivar named _someVariable, and a custom setter would usually have a parameter named someVariable
-(void)setSomeVariable:(NSString *)someVariable {
_someVariable = someVariable;
}
Also note that providing custom setter and getter methods for a particular property indicates to the Xcode compiler to not provide the implicit ivar (here _someVariable). In the case of readonly properties, the same if true if you provide just the getter method.
WWDC 2012 session 405 provides a lot of details around Objective-C constructs for modern versions of the compiler.
EDIT
As H2CO3 has suggested in his answer, the code I wrote assumes you're using ARC. If you are using MRC, the setter method would rather be :
-(void)setSomeVariable:(NSString *)someVariable {
[someVariable retain];
[_someVariable release];
_someVariable = someVariable;
}

What is the -> operator doing in -copyWithZone:? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Arrow operator (->) usage in C
Dot (“.”) operator and arrow (“->”) operator use in C vs. Objective-C
I'm a newbie looking at a freeware/open-source program last updated in 2008, and I don't recognize the -> in the following notation:
- (id)copyWithZone:(NSZone *)zone
{
GFIPGeniusItem * newItem = [[[self class] allocWithZone:zone] init];
newItem->_stringValue = [_stringValue copy];
newItem->_imageURL = [_imageURL copy];
newItem->_webResourceURL = [_webResourceURL copy];
newItem->_speakableStringValue = [_speakableStringValue copy];
newItem->_soundURL = [_soundURL copy];
return newItem;
}
I'm assuming it's allowing some sort of shortcut, but I'd love to specifically what it does.
It's a way to directly access an instance variable within an ObjC object from outside that object. (The syntax and -> is borrowed from C structs, behaving as if the reference were a pointer-to-structure).
This access mechanism is almost vestigial at this point, and very uncommonly seen in modern ObjC code, because good encapsulation requires the use of accessors and properties, not touching instance variables directly. It's legitimate in some very special cases, though, and this is one of them:
When copying an object, you want to get a resulting copy that matches exactly the state of the current self. The cleanest way of achieving this is often to set the copy's ivars explicitly, to prevent any side-effects that the init overloads or accessors might cause. It's "safe" because the code doing it is still located within the class that's in question, so if you needed to change or add ivars, you could update this code as well with the knowledge of anything else that might require.
Doing this from outside the class in question is bad form, and there's no good reason to do it.
In Objective-C you have some kind of two variable type accessors. The one everybody should know is the "." one (e.g. Class.variable). This type calls either the appropriate getter or setter.
Now, the other type - the one you asked for - is for in-class usage. Obviously, as the getter or setter gets called automatically with the "." notation you need a way to set the variable without a setter (calling the setter in the setter itself results in an endless loop). Therefore, this "->" notation is used -> simply, it is the direct-access mode.
Usually, Objective-C the variable name for both notations is the same but some prefer to have the in-class notation variable name beginning with "_". This is achieved by editing the #synthesize variable line to #synthesize variable = _variable.
That's a pointer indirection operator. a->b means the same thing as (*a).b (where the . is the structure member access operator, not Objective-C's property dot syntax).
When you say:
newItem->_stringValue
you're directly accessing the _stringValue instance variable of the object to which newItem points.
The -> operator is very common in C++, but not so much in Objective-C.
In Objective C, like in C++, the p->m notation is equivalent to (*p).m This is, the dereference of the pointer to the base type followed by a call to the corresponding method or property.
So in your case, using the other notation it would look like this:
(*newItem)._stringValue = [_stringValue copy];
(It's more common to use the -> operator)

Objective C - Synthesize property [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Prefixing property names with an underscore in Objective C
When synthesizing properties I found out that someone is doing:
#synthesize myVar = _myVar;
what is "_myVar" and which is the difference with simply doing :
#synthesize myVar;
Lastly when I should prefer the first solution to the last one?
Thanks
Luca
What _myVar really is in your example, is the name of the ivar that is backing your property. By default, when you synthesize a property, an ivar of the same name is created for you. So, you can use your property to set your ivar through setter/getter or the _myVar to directly access your variable (bypassing KVC/KVO of course).
EDIT:
From Apple's Coding Guidelines for Cocoa
...In many cases, when you use a declared property you also synthesize
a corresponding instance variable.
Make sure the name of the instance variable concisely describes the
attribute stored. Usually, you should not access instance variables
directly, instead you should use accessor methods (you do access
instance variables directly in init and dealloc methods). To help to
signal this, prefix instance variable names with an underscore (_)...
If you want to use some existing data member in setter and getter then it can be specify like that.
e.g. #synthesize personName=pName;
by this we can use pName instead of personName as per our convenience.
It the name of the private variable.
Se my answer on an other post: answer