Hello,
I’ve been playing around the Kotlin and I’m really liking what I’m seeing. I think the language strikes a real nice balance between expressiveness and practicality, I particularly think the emphasis on making sure the code is readable and has few gotchas is a really good idea.
Anyway, I was playing around and couldn’t work out how to do the equivalent of the following (very common) Java code.
class MyMap {
public static final DEFAULT_CAPACITY = 16;
public MyMap() {
this(DEFAULT_CAPACITY);
}
public MyMap(int capacity) {
…
}
}
The issue is defining a constant inside the class and using as a default constructor parameter. i.e. you might try this …
class MyMap(val capacity: Int = DEFAULT_CAPACITY) {
val DEFAULT_CAPACITY = 16
}
But the value isn’t in scope … You might try to do it Scala style with a companion object …
class MyMap(val capacity: Int = MyMap.DEFAULT_CAPACITY) {
…
}
object MyMap {
val DEFAULT_CAPACITY = 16
}
But it seems you can’t have companion objects named the same as your classes … meaning you need a specially named companion object just for that single constant value … which is a bit yuk.
You can of course, introduce it top-level …
val DEFAULT_CAPACITY = 16
class MyMap(val capacity: Int = DEFAULT_CAPACITY) {
…
}
But now you’ve cluttered up the global namespace with a constant that only makes sense for the MyMap class … you can hide the top-level item as private … but now people can’t explicitly get hold of the default capacity if they need it for some reason.
Anyone know any solutions I’ve not thought of?
Cheers
Tomsk