In Kotlin, how to delegate to an interface and provide only a no-arg public constructor? - guava

The problem arises from the fact that Kotlin class delegation allows to delegate only to constructor parameters, thus seemingly forcing you to provide constructor with an argument.
Below is my original question pertaining to a concrete use case of this problem.
I want to do the following:
val myTable1: MyTable = MyTable()
where
MyTable inherits from ImmutableTable (src) or at least Table
and I do not have to manually delegate all the Table methods to some base implementation.
I also want to avoid the following:
val myTable2: MyTable = MyTable.build()
i.e. I do not want to be forced to use companion objects / static factory methods.
I tried to extend ImmutableTable, but I am getting This type has a constructor, and thus must be initialized here.
I tried to extend Table interface and delegate to it (to avoid reimplementing methods) but then I am forced to provide an instance of Table as constructor parameter. I cannot just initialize it in init {} block.
Please see this gist for my exact attempts.
Kotlin version used: 1.0.2

As mentioned in comments, Guava has ForwardingTable that can accomplish this. But here's another option that should work even for interfaces where there isn't a "forwarding" version defined.
class MyTable private constructor(table: Table<Int, Int, Int>) : Table<Int, Int, Int> by table {
constructor() : this(TreeBasedTable.create()) // or a different type of table if desired
}

Related

Why should we use the 'override' key word in Kotlin for abstact class members?

If the base class has an abstract method or property, than these members must be overriden in the child class. The documentation says that i must use key word 'override' every time for such members, because i must implement methods or initialize properties in the child class. For example:
abstract class Dwelling {
abstract val buildingMaterial: String
abstract fun hasRoom() : Boolean
}
class RoundHut : Dwelling() {
override val buildingMaterial = "Stone"
override fun hasRoom() : Boolean {
return true
}
}
If an abstract method and a property must be overriden and implemented in child class any way (and compiler know this), than why we should write 'override' key word every time?
When you find yourself reading and understanding the implementing class, you have the explicit information that you're currently investigating an overridden one as it's explicitly marked as such. Kotlin likes to make things explicit and the documentation states
[...] we stick to making things explicit in Kotlin. So, Kotlin requires explicit modifiers for overridable members (we call them open) and for overrides
Java has an #Override annotation that is optional and not used by everyone although it has been considered a best practice (even as per Effective Java). Kotlin goes one step further by making it a compiler-enforced requirement.

Mark Haxe Class for forced extend?

Is there a compiler meta for Class declaration, that prevents creating Class instance before extending it? In other words - some sort of opposite of #:final meta.
Like so (last line of code):
class A {
// ...
}
class B extends A {
// ...
}
// ...
var b = new B(); // OK
var a = new A(); // induce compiler-error
Simply don't declare a constructor at all for class A
Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:
Here's an example of no constructor. Of note is that A simply doesn't have a constructor, and B simply doesn't call super(). Other than that, everything else works as you'd expect.
Here's an example of a private constructor. You still can't instantiate a new A(), but you do still need to call super() from B's constructor.
Technicalities:
Use of some features (like a default value on a member variable) will cause A to get an implicit constructor, automatically. Don't worry, this doesn't affect constructability or whether you need to call super(). But know that it is there, and if necessary an implicit super() call is prepended to B's constructor. See the JS output to verify this.
In any case, know that you can still instantiate an A at runtime with var a = Type.createInstance(A,[]); as compile-time type checks do not limit RTTI.
Related discussion:
Aside from private/no constructor, Haxe doesn't have a formal notion of abstract classes1 (base classes not expected to be instantiated) or abstract methods2 (functions on abstract base classes with no implementation that must be implemented by a derived class.) However, Andy Li wrote a macro for enforcing some of those concepts if you use them. Such a macro can detect violations of these rules and throw compile-time errors.
1. Not to be confused with Haxe abstracts types, which are an entirely different topic.
2. Not to be confused with virtual functions, which wikipedia describes as a function which can be overridden (though various docs for various languages describe this highly loaded term differently.)
One way of achieving this is to create private Class constructor:
class A {
private function new() {
// ...
}
}
// ...
var a = new A(); // Error: Cannot access private constructor

What is the use of private constructor in Scala?

In Java, one of its most common usage is to define a Singleton class. However, since there are no "static" classes in Scala, what are some examples of usages of the Private Constructor?
You can access private constructors in the companion object of a class.
That allows you to create alternative ways of creating a new instance of your class without exposing the internal constructor.
I came up with a very quick example of how one might make use of this:
class Foo private(s: String)
object Foo {
def apply(list: Seq[String]): Foo = {
new Foo(list.mkString(","))
}
}
Now you can create new instances of Foo without the new keyword and without exposing the internal constructor, thereby encapsulating the internal implementation.
This can be especially important, as internal implementations might change in the future while the public facing API should remain backwards compatible
The use cases of the private constructors are mostly the same as in Java: sometimes you need a full control of how the instances of your classes are created. Consider scala.immutable.Vector. Its constructor is rather complicated:
final class Vector[+A] private(val startIndex: Int, val endIndex: Int, focus: Int)
This constructor is a complex implementation detail which is likely to be changed in the future and therefore should not be exposed to users. Instead, you provide simple factory methods which hide all that complexity of creating instances of vectors: Vector.apply(), Vector.tabulate(), Vector.fill(), ...

Different field instances in class and parent/Call super constructor with method

I am trying to call the super constructor from a class using a method. The whole setup looks like this:
class Straight(hand: Hand) extends Combination(Straight.makeHandAceLowIfNeeded(hand), 5)
object Straight {
private def makeHandAceLowIfNeeded(hand: Hand): Hand = {
...
}
}
While this does compile, it has some rather odd runtime behaviour. While debugging, I noticed that the Straight instances have the "hand" property defined twice. Can somebody tell me what is going on, and what the proper way is to call the super constructor with different arguments?
In my use case, I want to call the super constructor with a modified hand in which I replaced a card compared to the original constructor argument.
Debugger screenshot with duplicate field:
.
It's a perfectly fine way to call the superclass constructor. These are two private fields and they don't conflict, though you can rename one of them to avoid confusion during debugging (or if you want to access the superclass' value from the subclass). However, the field should only be generated for a class parameter if it's used outside a constructor, and in your case it doesn't appear to be. Did you simplify the definition of Straight?

Scala: invoking superclass constructor

I am experiencing a weird behavior by Scala handling of superclass constructors.
I have a really simple class defined in the following way
package server
class Content(identifier:String,content:String){
def getIdentifier() : String = {identifier}
def getContent() : String = {content}
}
and a simple subclass
package server
class SubContent(identifier:String, content:String) extends Content(identifier, content+"XXX")){
override def getContent():String = {
println(content)
super.getContent
}
}
What's really strange is that in the subclass there are duplicates of the superclass attributes, so if i create a new object
var c = new SubContent("x","x")
the execution of
c.getContent
first prints out "x" (The valued provided to the subclass constructor), but returns "xXXX" (The value provided to the superclass constructor).
Is there any way to avoid this behavior? Basically what I'd like to have is that the subclass does not create its own attributes but rather just passes the parameters to the superclass.
It's doing exactly what you told it to do. You augmented the 2nd constructor parameter when passing it on to the superclass constructor and then you used the superclass' getContent to provide the value returned from the subclass' getContent.
The thing you need to be aware of is that constructor parameters (those not tied to properties because they're part of a case class or because they were declared with the val keyword) are in scope throughout the class body. The class' constructor is that part of its body that is outside any method. So references to constructor parameters in method bodies forces the constructor parameter to be stored in a field so it can have the necessary extent. Note that your println call in getContent is causing such a hidden constructor parameter field in this case.
Replying to comment "Is there an alternative way to define it in order to avoid this? Or at least, if I never refer to the parameters of the subclass constructors their fields will be allocated (Wasting memory)?":
If the only references to plain constructor parameters (*) is in the constructor proper (i.e., outside any method body, and val and var initializers don't qualify as method bodies) then no invisible field will be created to hold the constructor parameter.
However, If there's more you're trying to "avoid" than these invisible fields, I don't understand what you're asking.
(*) By "plain constructor parameters" I mean those not part of a case class and not bearing the val keyword.