Kotlin protected property can not be accessed in other module - kotlin

Just when I thought I understood it, I got the following issue.
I have a base class in another module (called base here)
It looks like that:
open class BaseTest {
companion object {
lateinit var baseTest: BaseTest
}
protected open var someProperty: String? = "base"
}
I want to set that property and made it protected so my extended class in another module could access it.
class Extended: BaseTest() {
fun extendedCall() {
BaseTest().someProperty = "extended"
baseTest.someProperty = "extended"
}
}
However, neither the static one, not the direct property is accessable stating the following error:
Cannot access 'someProperty': it is protected in 'BaseTest'
But shouldn't that be accessable since Extended inherents from BaseTest()? I mean the definition of protected is "Declarations are only visible in its class and in its subclassess" so what have I missed? It even doesn't work in the same module so that's not the cause.
What am I missing?

BaseTest().someProperty = "extended"
Here you make a new BaseTest object by calling the constructor BaseTest() and you are not allowed to access protected properties of other BaseTest objects.
baseTest.someProperty = "extended"
the static BaseTest object is also another object and not the Extended object itself.
Being protected merely makes it possible to do
someProperty = "extended"
or the equivalent
this.someProperty = "extended"
That is, access the property of this object.

I believe the protected modifier doesn't work like that in Kotlin.
The documentation says:
The protected modifier is not available for top-level declarations.
But I agree it's quite confusing as written. It appears the documentation focuses more on the Outter/Inner class relationship via the this keyword.

Related

Overriding the property and renewing the property?

On my sub class if I override the property, we call it property XYZ is overriding the property from the base class. What do you call if property is getting renewed by using new keyword? Renewed?
This using of the new keyword as modifier is called member hiding.
From MSDN Documentation:
When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version. Although you can hide members without using the new modifier, you get a compiler warning. If you use new to explicitly hide a member, it suppresses this warning.
To hide an inherited member, declare it in the derived class by using the same member name, and modify it with the new keyword.
public class BaseC
{
public int x;
public void Invoke() { }
}
public class DerivedC : BaseC
{
new public void Invoke() { }
}
For more information when to use override and when to use new keyword modifier you can read in MSDN too.

VB.NET access level of interface declaration not matching access level of implementation [duplicate]

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class
The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.
From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...
There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.
When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.
The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

Swift readonly external, readwrite internal property

In Swift, what is the conventional way to define the common pattern where a property is to be externally readonly, but modifiable internally by the class (and subclasses) that own it.
In Objective-C, there are the following options:
Declare the property as readonly in the interface and use a class extension to access the property internally. This is message-based access, hence it works nicely with KVO, atomicity, etc.
Declare the property as readonly in the interface, but access the backing ivar internally. As the default access for an ivar is protected, this works nicely in a class hierarchy, where subclasses will also be able to modify the value, but the field is otherwise readonly.
In Java the convention is:
Declare a protected field, and implement a public, read-only getter (method).
What is the idiom for Swift?
Given a class property, you can specify a different access level by prefixing the property declaration with the access modifier followed by get or set between parenthesis. For example, a class property with a public getter and a private setter will be declared as:
private(set) public var readonlyProperty: Int
Suggested reading: Getters and Setters
Martin's considerations about accessibility level are still valid - i.e. there's no protected modifier, internal restricts access to the module only, private to the current file only, and public with no restrictions.
Swift 3 notes
2 new access modifiers, fileprivate and open have been added to the language, while private and public have been slightly modified:
open applies to class and class members only: it's used to allow a class to be subclassed or a member to be overridden outside of the module where they are defined. public instead makes the class or the member publicly accessible, but not inheritable or overridable
private now makes a member visible and accessible from the enclosing declaration only, whereas fileprivate to the entire file where it is contained
More details here.
As per #Antonio, we can use a single property to access as the readOnly property value publicly and readWrite privately. Below is my illustration:
class MyClass {
private(set) public var publicReadOnly: Int = 10
//as below, we can modify the value within same class which is private access
func increment() {
publicReadOnly += 1
}
func decrement() {
publicReadOnly -= 1
}
}
let object = MyClass()
print("Initial valule: \(object.publicReadOnly)")
//For below line we get the compile error saying : "Left side of mutating operator isn't mutable: 'publicReadOnly' setter is inaccessible"
//object.publicReadOnly += 1
object.increment()
print("After increment method call: \(object.publicReadOnly)")
object.decrement()
print("After decrement method call: \(object.publicReadOnly)")
And here is the output:
Initial valule: 10
After increment method call: 11
After decrement method call: 10

Interface behavior is dfferent in VB.Net

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class
The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.
From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...
There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.
When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.
The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

Inheriting ConstructorArguments in Ninject

I'm trying to find a method of passing a constructor argument to the constructors of child classes.
These objects are immutable so I'd prefer to use constructor arguments.
The issue I have encountered is that ConstructorArgument does not inherit to child instantiations and the following statements are not interchangeable:
_parsingProcessor = _kernel.Get<IParsingProcessor>(new ConstructorArgument("dataFilePath", dataFilePath);
and
_parsingProcessor = _kernel.Get<IParsingProcessor>(new Parameter("dataFilePath", dataFilePath, true);
So, how can get an inheritable ConstructorArgument and when does it makes sense, if ever, to new the Parameter class?
Yes, you can do this, but it's probably not what you really want. If the container is not actually responsible for instantiating its own dependencies, then its dependencies probably shouldn't be sharing its constructor arguments - it just doesn't make sense.
I'm pretty sure I know what you're trying to do, and the recommended approach is to create a unique binding specifically for your one container, and use the WhenInjectedInto conditional binding syntax, as in the example below:
public class Hello : IHello
{
private readonly string name;
public Hello(string name)
{
this.name = name;
}
public void SayHello()
{
Console.WriteLine("Hello, {0}!", name);
}
}
This is the class that takes a constructor argument which we want to modify, depending on who is asking for an IHello. Let's say it's this boring container class:
public class MyApp : IApp
{
private readonly IHello hello;
public MyApp(IHello hello)
{
this.hello = hello;
}
public virtual void Run()
{
hello.SayHello();
Console.ReadLine();
}
}
Now, here's how you do up the bindings:
public class MainModule : NinjectModule
{
public override void Load()
{
Bind<IApp>().To<MyApp>();
Bind<IHello>().To<Hello>()
.WithConstructorArgument("name", "Jim");
Bind<IHello>().To<Hello>()
.WhenInjectedInto<MyApp>()
.WithConstructorArgument("name", "Bob");
}
}
Basically all this binding is doing is saying the name should be "Jim" unless it's being requested by Hello, which in this case it is, so instead it will get the name "Bob".
If you are absolutely certain that you truly want cascading behaviour and understand that this is very dangerous and brittle, you can cheat using a method binding. Assuming that we've now added a name argument to the MyApp class for some unspecified purpose, the binding would be:
Bind<IHello>().ToMethod(ctx =>
ctx.Kernel.Get<Hello>(ctx.Request.ParentContext.Parameters
.OfType<ConstructorArgument>()
.Where(c => c.Name == "name")
.First()));
Please, please, make sure you are positive that this is what you want before doing it. It looks easy but it is also very likely to break during a simple refactoring, and 95% of the "customized dependency" scenarios I've seen can be addressed using the WhenInjectedInto binding instead.