Kotlin: variable in enum class can't be changed after initialization - kotlin

When writing this example into the IDE:
enum class EnumTest {
FOO, BAR;
lateinit var foobar: String
}
I get the message With old Native GC, variable in enum class can't be changed after initialization on the "foobar" variable. I can't find anything about this message online. Also everything seems to work just fine, so my question is:
When and how does this affect me?
Thank you!

You could declare your values in a singleton object, set them there and reference it in the enum.
object Constants {
var FOO_STR = "bla"
var BAR_STR = "bar"
}
enum class EnumTest(val foobar: String) {
FOO(Constants.FOO_STR),
BAR(Constants.BAR_STR);
}
This code should work but also smells fishy.
Since an enum has an immutable flavor by design, I would not recommend this approach. I feel bad about posting this... but if your main problem is the resource heavy loading of these constants, maybe you do not need an enum to store those properties. Maybe just think of a simple singleton container with simple (named) properties.

Related

Kotlin: does it make sense a property with private get and public set?

I am new to Kotlin, and I have been experimenting with the language. In Kotlin in Action, it says the following:
The accessor’s visibility by default is the same as the property’s. But you can change
this if you need to, by putting a visibility modifier before the get or set keyword.
I have tried to create a property that has a private getter and a public setter, as follows:
class BackingField {
var aProperty = 1
private get
set(value) {
field = value + 1
}
}
However, IntelliJ is suggesting me to remove the private modifier before get. Is is possible to have a public property with a private getter and a public setter? If so, what are some common applications of such entity? If not, could we conclude that what is stated in the book is partially wrong?
The book is not wrong per se. Because you can actually change the visibility on both the get and set but the set can't be more visible than the get according to this question:
Private getter and public setter for a Kotlin property
Remember that books and IDEs offer recomendations and not good design based on what you do.
The set can't be more visible than the get, as other said, but then remember that properties and backing fields is just an abstraction. You can have no backing field and declare your interface setter and getter methods with the access restrictions you wish for.
Given this use case, it's obvious that you have special requirements. I.e. the data is not just set, but also incremented by 1. So your external interface would probably have another name for it as well.
Having the syntac object.field = x invoke a setter function is suspect as well, cause the syntax implies no function invocation, as in java or C/C++ structs. it can bite you horribly and make you miss the fact that the assignment invokes a setter somewhere in your code - I would consider it bad design.
The feature of properties and getters/setters works mostly if you are working with data objects and pokos (plain old kotlin objects) only. It's very good for those cases, and can save you time, but once you stray off into more complex scenarios, as you are doing, it's weakness will begin to show.
In this case you don't need a setter, because the class will have access to it privately. The getter though, is something you have to define, and perhaps give a more apropriate name, like setAndIncrement.
class BackingField {
private var aProperty = 1
fun setAProperty(value:Int) { aProperty=value+1}
private fun getAProperty():Int { return aProperty }
fun print() {println(aProperty)}
}
fun main() {
var f = BackingField()
f.print()
f.setAProperty(10)
f.print()
println(f.aProperty) // Won't compile
}

Getting annotation of enum value

I know how to get an annotation of an enum value in Java.
However Kotlin has its own reflection library and I feel there should be a better way to do the job.
Could please anybody post an example.
Just to be specific let's define an enum class
enum class Enum {
#SerialName("constant")
Constant
}
I need a function f(e: Enum): String so that f(Enum.Constant) == "constant".
You can use a similar approach with java by getting the field by name and then reaching out to the annotation using annotation class.
So if you have below enum and annotation class definitions;
enum class Enum {
#SerialName("constant")
Constant
}
annotation class SerialName(val value: String)
Then you can define the below function and call it as shown below;
fun getAnnotationValue(enum:Enum):String = enum.declaringClass.getField(enum.name).getAnnotation(SerialName::class.java).value
fun main(args: Array<String>) {
println(getAnnotationValue(Enum.Constant))
}
Hope this helps.
I did only a little research here, but it appears there isn't support for this in the Kotlin reflection library. In fact, I discovered the linter doesn't even correctly suggest an annotation target of FIELD for your annotation if you give it one that doesn't work for Enum values, and instead incorrectly offers to automatically add a target of CLASS.
The problem is that Enum values are basically static member fields, which don't exist in Kotlin except in Enum classes. And the reflection classes don't seem to provide a way to access this special case.
I am struggling however to come up with a use case for Enum value annotations that can't be solved using properties in the Enum constructor(s).
enum class MyEnum(val someConstant: String? = null) {
SomeValue("myConstant")
}

How to test if lateinit var is initialized from outside the class? - Kotlin

This SO post outlines how to test if a lateinit var has been initialized. However, in the example, the lateinit var is conveniently located within the same class.
How do you do the same thing from outside the class? This is the situation I have:
Foo.kt
class Foo {
lateinit var foo: String
}
Bar.kt
class Bar {
fun doSomething() {
val foo = Foo().foo
if (::foo.isInitialized) { // Unsupported [reference to variables aren't supported yet]
Log.i("TAG", "do something")
}
}
}
What's the workaround for this?
If this was going to work, you'd need to do
val foo = Foo()
if (foo::foo.isInitialized)
//...
The way you're doing it, you're trying to get a property reference of your local variable, which isn't a property. That's why the error says "reference to variables aren't supported yet" rather than "backing field not accessible at this point". Also, you'd be accessing the getter of the lateinit property when assigning the local variable, so it would fail if it weren't initialized yet.
But it doesn't work because of compiler limitations. You could simply add a getter
val fooReady: Boolean get() = ::foo.isInitialized
But I would say the design has very poor encapsulation if outside classes need to check whether a particular public property is initialized yet. In my opinion, any use of isInitialized is a code smell to begin with. If you need to guard calls to the getter with isInitialized, you might as well make the property nullable instead. Then you can use the familiar idioms of null checks instead of resorting to reflection, and it will work in a familiar way even for external classes that access it.
If object of another class has to make a decision based on whether or not the property is initialised, then having this property initialised - or answering whether or not it has already been initialised - is a public business capacity of your object and therefore I would recommend you to simply make it a part of your public API via public fun isFooInitialised(): Boolean function that utilises the fact that the object itself can inspect the state of its lateinit properties.

Chain up to 'Gtk.Box.new' not supported

I'm new to Vala and so far I think it's pretty cool but I'm having trouble understanding inheritance. I read here that I should use base() to call the parents constructor. Alright, cool, seems understandable but It din't work for me. I kept getting the error on the title. Here is my snippet to show:
public class MyBox : Gtk.Box {
public MyBox(Gtk.Orientation orientation, int spacing) {
// I have to this
this.set_orientation(orientation);
this.set_spacing(spacing);
// I want to do this:
base(orientation, spacing);
//workaround is this:
Object(orientation: orientation, spacing: spacing);
}
}
Please help me understand why Object(....) works but not base(...)
Shouldn't it be the same thing?
This is due to implementation of the C code. When Vala generates a constructor, it generates two C functions a _new function that allocates memory and calls the _construct and a _construct function that initialises the object. When you case the base constructor using base(), it needs a matching _construct function to call. Not all the classes written in C have this; in the VAPI file, you will find has_construct_function = false for some constructors. If this is the case, no chain-up can be done. The base GObject can set properties from arguments, so this becomes the only way to set defaults in the base class.

Why no stored type properties for classes in swift?

Working through The Swift Programming Language, I was surprised to see that, unlike structures and enumerations, classes do not support stored type properties.
This is a common feature of other OO languages so I assume there was a good reason they decided not to allow it. But I'm not able to guess what that reason is, especially since structures (and enumerations) have them.
Is it simply that it's early times for Swift and it just hasn't been implemented yet? Or is there a deeper reason behind language design decision?
BTW, "stored type property" is Swift terminology. In other languages these might be called class variables. Example code:
struct FooStruct {
static var storedTypeProp = "struct stored property is OK"
}
FooStruct.storedTypeProp // evaluates to "struct stored property is OK"
class FooClass {
class var computedClassProp: String { return "computed class property is OK" }
// class var storedClassProp = "class property not OK" // this won't compile
}
FooClass.computedClassProp // evaluates to "computed class property is OK"
Edit:
I now realize this limitation is trivial to work around, e.g., by using a nested structure with stored properties:
class Foo {
struct Stored {
static var prop1 = "a stored prop"
}
}
Foo.Stored.prop1 // evaluates to "a stored prop"
Foo.Stored.prop1 = "new value"
Foo.Stored.prop1 // evaluates to "new value"
That seems to preclude their being some deep inscrutable language design reason for this limitation.
Given that and the wording of the compiler message that Martin Gordon mentions, I have to conclude that this is simply something (minor) left out.
The compiler error is "Class variables not yet supported" so it seems like they just haven't implemented it yet.
Extending the OP's nested struct trick for simulating stored type properties, you can go further and make it look like a pure stored type property from outside the class.
Use a computed getter and setter pair like:
class ClassWithTypeProperty
{
struct StoredTypeProperties
{
static var aTypeProperty: String = "hello world"
}
class var aTypeProperty: String
{
get { return self.StoredTypeProperties.aTypeProperty }
set { self.StoredTypeProperties.aTypeProperty = newValue }
}
}
Then you can do:
println(ClassWithTypeProperty.aTypeProperty)
// Prints "hello world"
ClassWithTypeProperty.aTypeProperty = "goodbye cruel world"
println(ClassWithTypeProperty.aTypeProperty)
// Prints "goodbye cruel world"
“For value types (that is, structures and enumerations), you can define stored and computed type properties. For classes, you can define computed type properties only."
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/cn/jEUH0.l
I think it's easy for Apple's Engineers to add stored type properties to classes, but not yet we know, maybe never in my opinion. And that's why there are labels ( static and class ) to distinguish them.
The most important reason may be it:
To avoid different objects have shared changeable variable
we know :
static let storedTypeProperty = "StringSample" // in struct or enum ...
can be replaced by
class var storedTypeProperty:String {return "StringSample" } // in class
but
static var storedTypeProperty = "StringSample"
is harder to be replaced by class phrase in class.
// I am new to Swift Programming Language actually and it's my first answer in Stack OverFlow. Glad to discuss with you. ^^