Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a property without accessors in Kotlin?

I am using a Kotlin class from Java code. My Kotlin class looks like:

class Something {
    var a = 0
}

I want to be able to access a from Java code like

s = new Something();
s.a = 5;

however, I only have s.getA() and s.setA(5). Is there any way to make this property directly settable and gettable from Java? Obviously we can't have custom getter and setter in this case.

like image 700
Randy Sugianto 'Yuku' Avatar asked Mar 17 '16 07:03

Randy Sugianto 'Yuku'


People also ask

Can you declare a class without a body in Kotlin?

In Kotlin both the header and the body are optional; if the class has no body, curly braces can be omitted.

What is accessors in Kotlin?

1.0. interface Accessor<out V> Represents a property accessor, which is a get or set method declared alongside the property. See the Kotlin language documentation for more information.

Are getters and setters necessary in Kotlin?

In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.


1 Answers

You can annotate a property with the @JvmField annotation to expose it as a Java field.

If you need to expose a Kotlin property as a field in Java, you need to annotate it with the @JvmField annotation. The field will have the same visibility as the underlying property. You can annotate a property with @JvmField if it has a backing field, is not private, does not have open, override or const modifiers, and is not a delegated property.

like image 104
Cootri Avatar answered Nov 14 '22 21:11

Cootri