How to define protected field with public accessor in Kotlin - kotlin

I have the following situation:
data class Person(val name: string=""):Entity { }
open class Entity() { var id: Long=0 }
In this way, id is a public property, and the associated field is private (is not visible in Person class).
I'm working on an annotation processor and the annotation that I've defined works on fields. How can I define the property id as protected field with public accessor?

You can set as a public variable and work with the scope of its setter, in this case, set the setter as protected using:
var yourField: Any = /** initial value **/
protected set
Read more about Visibility modifiers here

Related

Jackson fails with "Cannot construct instance of WorkpoolId (although at least one Creator exists): no int/Int-argument constructor/factory"

I have the following class
public class WorkpoolId implements Serializable {
#NotNull
private Long id = null;
#JsonCreator
public WorkpoolId(#JsonProperty("workpoolId") long id) {
this.id = Long.valueOf(id);
}
public WorkpoolId(Long id) {
this.id = id;
}
public WorkpoolId(String id) {
this.id = Long.valueOf(id);
}
private WorkpoolId() {
}
}
when mapping
"workpoolId":1
to this class I get a
javax.ws.rs.ProcessingException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of WorkpoolId (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
Why is jackson not able to use the long constructor for the number value?
It fails because your WorkpoolId does not have access to field workpoolId it is not in its context anuymore. When your JSON is deserialized it could be deserialized either as an
independent object (having no field workpoolId, it IS the workbookId)
field object value in an object containing -say Data - it that might be named as workpoolId.
Now the use of workbookId could be usable for the JsonCreator in Data when constructing its field workpoolId.
To clarify this a bit, here is an example of possible Data class:
#Getter #Setter
public class Data {
private WorkpoolId workpoolId;
#JsonCreator // here it is a property!
public Data(#JsonProperty("workpoolId") long id) {
this.workpoolId = new WorkpoolId(id);
}
}
Json would be like {"workpoolId":1}
To have it work just remove the annotation #JsonProperty("workpoolId") from the attribute declaration. Actually the whole #JsonCreator annotation is not needed.

Object obtained from WCF service has null private fields, even though they are initialized in the class [duplicate]

I need to initialize private readonly field after Deserialization. I have folowing DataContract:
[DataContract]
public class Item
{
public Item()
{
// Constructor not called at Deserialization
// because of FormatterServices.GetUninitializedObject is used
// so field will not be initialized by constructor at Deserialization
_privateReadonlyField = new object();
}
// Initialization will not be called at Deserialization (same reason as for constructor)
private readonly object _privateReadonlyField = new object();
[DataMember]
public string SomeSerializableProperty { get; set; }
[OnDeserializing]
public void OnDeserializing(StreamingContext context)
{
// With this line code even not compiles, since readonly fields can be initialized only in constructor
_privateReadonlyField = new object();
}
}
All what I need, that after Deserialization _privateReadonlyField is not null.
Any suggestions about this - is it possible at all?
Or I need to remove "readonly" key, which is not a good option.
Serialization is able to read in values for read-only fields because it uses reflection, which ignores accessibility rules. It can be argued that the following is, therefore, justified as part of the serialization process, even though I would recommend strongly against it in almost any other circumstance:
private readonly Doodad _oldField;
[OptionalField(VersionAdded = 2)]
private readonly Widget _newField;
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
if (_oldField != null && _newField == null)
{
var field = GetType().GetField("_newField",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly |
System.Reflection.BindingFlags.NonPublic);
field.SetValue(this, new Widget(_oldField));
}
}
Any field declared as private readonly can be instantiated in the same line where it was declared or inside a constructor. Once that is done it cannot be changed.
From MSDN:
The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
That means that you will have to remove readonly keyword to get it to work.

How to access a non-public variable in a base class?

I'm in a method of a derived class, loosely as follows:
Class Base
{
private:
int variableIWantToAccess;
}
Class Derived : public Base
{
public someMethod() {
variableIWantToAccess++; <<-----ERROR
}
How do I access the variable that's declared in the base class? I'm unable to access it because it is private.
You should declare it as protected instead of private.
Protected members of a class are accessible for the class descendants only.
Leave the field private and create a pair of protected getter / setter methods instead (for the same reasons you wouldn't expose a public field).
Class Base
{
private:
int variableIWantToAccess;
protected:
int GetVariable() { return variableIWantToAccess; }
void SetVariable(int var) { variableIWantToAccess = var; }
}

Object reference not set to an instance of an object, Interface

I know that this is one of the most encountered error but I am really struggling to get around it.
i have a property on my Controller:
private readonly ISelectListFactory _selectFactory;
and a method that called to populate the viewbag
private void PopulateLists()
{
var continent = _selectFactory.GetItems();
}
and the interface
public interface ISelectListFactory
{
IEnumerable<SelectListItem> GetItems();
}
and in the controller constructor I have the following:
public LocationController(ISelectListFactory selectFactory)
{
_selectFactory = selectFactory;
}
but I am getting this error Object reference not set to an instance of an object and not sure how to overcome it.
Regards
Make sure you have instantiated this _selectFactory variable somewhere. Like for example:
_selectFactory = new SomeConcreteSelectListFactory();
or if you are using dependency injection you might configure your DI framework to inject it into the constructor:
public class HomeController: Controller
{
private readonly ISelectListFactory _selectFactory;
public HomeController(ISelectListFactory selectFactory)
{
_selectFactory = selectFactory;
}
... some controller actions where you could use the _selectFactory field
}

VB.Net and access via a variable of an interface type

How do I make the properties of a class available in an inheriting class, for a variable that is declared to be the type of one of the interfaces implemented by that class?
What I have done so far is to create an abstract class MyAbstract with the keyword MustInherit and in the inheriting class MyInheritingClass I have added inherits and then the name of the abstract class. Now this is all fine, but in my inheriting class, if I create an interface on that class MyInterface and use that interface elsewhere in my code, I have then found that I cannot see the properties from my abstract class, on the variable declared with that interface.
Am I doing something wrong here, or is there something else that I need to do?
An example would be as follows:
Public MustInherit Class MyAbstract
Private _myString as String
Public Property CommonString as String
Get
Return _myString
End Get
Set (value as String)
_myString = value
End Set
End Property
End Class
Public Class MyInheritingClass
Inherits MyAbstract
Implements MyInterface
Sub MySub(myParameter As MyInterface)
myParameter.CommonString = "abc" ' compiler error - CommonString is not a member of MyInterface.
End Sub
'Other properties and methods go here!'
End Class
So, this is what I am doing, but when I use MyInterface, I cannot see the properties of my Abstract Class!
Unless I've completely misunderstood your question, I'm not sure why you are confused by this behavior. Not only is that how it should work, but that is also how it works in c#. For instance:
class Program
{
private abstract class MyAbstract
{
private string _myString;
public string CommonString
{
get { return _myString; }
set { _myString = value; }
}
}
private interface MyInterface
{
string UncommonString { get; set; }
}
private class MyInheritedClass : MyAbstract, MyInterface
{
private string _uncommonString;
public string UncommonString
{
get { return _uncommonString; }
set { _uncommonString = value; }
}
}
static void Main(string[] args)
{
MyInterface test = new MyInheritedClass();
string compile = test.UncommonString;
string doesntCompile = test.CommonString; // This line fails to compile
}
}
When you access an object through any interface or base class, you will only ever have access to the members that are exposed by that interface or base class. If you need to access a member of MyAbstract, you need to cast the object as either MyAbstract or MyInheritedClass. This is true in both languages.