What is the use of open properties in Kotlin? - kotlin

I have been learning Kotlin and have come across the concept of open properties. Coming from C++, the concept of "open" makes sense, and extending that logic to properties does as well. However, I can't think of any case where an open val/var is actually necessary or useful. I understand when they make sense for interfaces, but not concrete classes. Furthermore, overriding getters/setters makes sense, but not redefining the property with a new backing field. For example, say you have this kind of class structure:
open class Foo {
open var str = "Hello"
}
class Bar : Foo() {
override var str = "world"
init {
println(str)
println(super.str) // Shows that Bar actually contains "hello" and "world"
}
}
To me, it would seem to be a far better design to make Foo take str as a constructor argument, for instance:
open class Foo(var str = "Hello") // Maybe make a secondary constructor
class Bar : Foo("world") // Bar has only 1 string
This is both more concise, and seems to often be a better design. This is also the way it tends to be done in C++, so maybe I just don't see the benefit of the other way. The only possible time I can see overriding a val/var with a new one is if it for some reason needs to use super's value, like in
override val foo = super.foo * 2
Which still seems pretty contrived.
When have you found this useful? Does it allow for greater efficiency or ease of use?

open fields let you re-define getter and setter methods. It's practically pointless if you just return constants. However altering getter / setter behavior has (infinite) potential, so I'll just throw some ideas:
// propagate get/set to parent class
class Bar : Foo() {
override var str
get() = super.str.toUpperCase()
set(value) {
super.str = value
}
}
// creates a backing field for this property
class Bar : Foo() {
override var str = "World"
get() = field.toLowerCase()
// no need to define custom set if we don't need it in this case
// set(value) { field = value }
}
// instead of writing custom get/set, you can also use delegates
class Bar : Foo() {
override var str by Delegates.observable("world"){ prop, old, new ->
println("${prop.name} changed from $old to $new")
}
}

Related

Access Implementation's property on variable of type Interface

I'm trying to access the delegate of the property (id) of a class (FooImpl). The problem is, this class implements an interface (Foo), and the property in question overrides a property of this interface. The delegate only exists in the class (not that it could exist in the interface).
The problem is that using the :: operator on a variable of type Foo always returns the property of Foo, not that of the actual instance. The problem in code:
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty0
import kotlin.reflect.jvm.isAccessible
interface Foo {
val id: Int
}
class FooImpl(
id: Int,
) : Foo {
override val id: Int by lazy { id }
}
val <T> KProperty<T>.hasDelegate: Boolean
get() = apply { isAccessible = true }.let { (it as KProperty0<T>).getDelegate() != null }
fun main() {
val foo: Foo = FooImpl(1)
println("foo::id.hasDelegate = ${foo::id.hasDelegate}")
println("(foo as FooImpl)::id.hasDelegate = ${(foo as FooImpl)::id.hasDelegate}")
}
This prints:
foo::id.hasDelegate = false
(foo as FooImpl)::id.hasDelegate = true
But this requires compile-time knowledge of the correct implementation. What I'm looking for is accessing the correct propert without having to specify FooImpl there.
The information is present at runtime because the least (!) intrusive workaround I have found so far is adding fun idProp(): KProperty0<*> to Foo and override fun idProp() = ::id to FooImpl and accessing the property using that.
Is there any better way than that?
I came up with this, but I don't know if there's a better way. The problem to work around is that getDelegate() has to return an actual instance of the delegate, so you need an instance of the class to be able to retrieve a delegate instance. It would really be nice if there was a hasDelegate property built in. Your version of hasDelegate will crash from the cast on unbound KProperty1's, which is all we have to work with when the specific class is unknown.
So to retrieve the delegate instance, we need to do search the class instance's member properties by name, which gives us a KProperty with covariant class type of the super-class type. Since it's covariant, we can call a consuming function like getDelegate() without casting to the invariant type. I think this logically should be safe, since we are passing an instance that we know has the matching type for the ::class that we retrieved the property with.
#Suppress("UNCHECKED_CAST")
fun <T: Any> KProperty1<T, *>.isDelegated(instance: T): Boolean =
(instance::class.memberProperties.first { it.name == name } as KProperty1<T, *>).run {
isAccessible = true
getDelegate(instance) != null
}
fun main() {
val foo: Foo = Foo2()
println("foo::id.hasDelegate = ${Foo::id.isDelegated(foo)}")
}
The problem here is that the owner of the property is resolved on compile time, not on runtime. When you do foo::id then foo (so FooImpl) become its bound receiver, but owner is still resolved to Foo. To fix this we wound need to "cast" property to another owner. Unfortunately, I didn't find a straightforward way to do this.
One solution I found is to use foo::class instead of foo::id as it resolves KClass on runtime, not on compile time. Then I came up with almost exactly the same code as #Tenfour04.
But if you don't mind using Kotlin internals that are public and not protected with any annotation, you can use much cleaner solution:
val KProperty0<*>.hasDelegate: Boolean
get() = apply { isAccessible = true }.getDelegate() != null
fun KProperty0<*>.castToRuntimeType(): KProperty0<*> {
require(this is PropertyReference0)
return PropertyReference0Impl(boundReceiver, boundReceiver::class.java, name, signature, 0)
}
fun main() {
val foo: Foo = FooImpl(1)
println(foo::id.castToRuntimeType().hasDelegate) // true
}
We basically create a new instance of KProperty, copying all its data, but changing the owner to the same type as its bound receiver. As a result, we "cast" it to the runtime type. This is much simpler and it is also cleaner because we separated property casting and checking for a delegate.
Unfortunately, I think Kotlin reflection API is still missing a lot of features. There should be hasDelegate() function, so we don't have to provide receivers, which is not really needed to check if property is delegated. It should be possible to cast KProperty to another type. It should be possible to create bound properties with some API call. But first of all, it should be possible to do something like: Foo::id(foo), so create KProperty of the runtime type of foo. And so on.

refer to property defined in interface, kotlin

guys, I am learning kotlin. From https://kotlinlang.org/docs/interfaces.html#properties-in-interfaces it says:
Properties declared in interfaces can't have backing fields, and
therefore accessors declared in interfaces can't reference them.
(I think the pronoun "them" at the end of quoted sentence should refer to "properties" rather than "fields". )
However the following code works. It seems that we can refer to properties. Why is print(prop) highlighted as red then?
interface MyInterface {
val prop: Int // abstract
val propertyWithImplementation: String
get() = "foo"
fun foo() {
print(prop) // this is highlighted red but it works. what's does the author want to say?
}
}
class Child : MyInterface {
override val prop: Int = 29
}
fun main() {
val c = Child()
c.foo()
}
Besides, I noticed that in the above example foo is not accessor. So I tried following example and it works too:
interface User {
val email: String
val nickname: String
get() = email.substringBefore('#') // aren't we referring to a property in accessor? why does this work then?
}
So what does the author want to say in here? what does "them" refer to?
"Them" in this sentence means "fields".
Property is basically a getter (setter) and it could be optionally backed by a field. For technical reasons interfaces can't hold fields, so properties in interfaces have to be "fieldless". Property has to be either abstract or its implementation can only use e.g. other properties/functions, but it can't store/read any data directly. Note that referencing other properties does not break above rule, because, as I said, property is mainly a getter/setter, not a field.
print(prop) is highlighted as red, because... well, this is how automatic highlighter colored it... :-)

Should I initialize variables on declaration, init block, constructor or lateinit? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I was wondering whats the difference between the 4 ways of initializing a variable (that I know of) in kotlin and which one would be the most accepted one.
First, initialize it on declaration:
class MyClass {
var textString: String = "Hello world"
}
Second, initialize it on the init block:
class MyClass {
var textString: String
init {
textString = "Hello world"
}
}
Third, use a constructor:
class MyClass {
var textString : String
constructor() {
this.textString = "Hello world"
}
}
Fourth, lateinit:
class MyClass {
lateinit var textString : String
fun initializeVariable() { //Assume this is called by something
this.textString = "Hello world"
}
}
I am mostly looking for the difference on compile time and the overall "good practice". I am aware of some "tricks" you can use, like using the init block to initialize some variables that are always the same regardless of the constructor used, but would that be the appropiate way of doing it?
From the technical standpoint, there's no much difference, at least in terms of simple properties like in the example - the property gets initialised anyway.
The lateinit modifier is a little exception here - it allows for a delayed initialization: it's like saying "I cannot set a meaningful value now, but I'm sure that it will be set before the first use". It is useful in Kotlin - Spring Framework integration, when one, for some reason doesn't want/cannot use constructor injection, and allows for property injection.
#Autowired lateinit var foo: Foo
or when using Spring's #Value annotation
#Value("\#{props.foo}") lateinit var foo: String
There's a difference, though, from the reader / maintainer point of view, and when you need some extra functionality, say precondition validation. As a rule of thumb initialise your properties as early as possible: the preferred way is in the primary constructor:
class Foo(var bar: String = "default value")
The reader of your code, maybe future you, won't have to jump trough the code to understand where does the "default value" come from - it's right in the constructor!
Additionally, client code, can easily change the value when constructing the object, or leave it default
// set new value
val foo: Foo = Foo(bar = "specific value other than default")
// leave the default
val defaultFoo: Foo = Foo()
Having the property initialised in class body, forces the client code to firstly create an instance with a default, and only then override.
val foo = Foo()
foo.bar = "not so default"
Additionally, if there're some preconditions which you like to check, it's easier to do this when setting the values in the primary constructor. E.g. the foo String property cannot be blank:
class Foo(var bar: String = "default") {
init {
require(bar.isNotBlank()) { "Bar cannot be blank" }
}
}
Where it's possible I'd go with constructor initialization.
Also, if you are willing to spend a few dollars on a book on good practices and patterns in Kotlin, I highly recommend Marin Moskała's Effective Kotlin https://leanpub.com/effectivekotlin
lateinit is irrelevant because it doesn't initialize anything.
Initialization on the same line is only for simple properties. You can use closures and then invoke them, like so val i = { // complex code }(), but it's ugly.
For a detail discussion of constructor vs init block, see this. The simplest way to understand the initialization order is to create a class with a primary, secondary and an init block, and then either use println or simply a debugger to follow the execution.

Extension fields in Kotlin

It's easy to write extension methods in Kotlin:
class A { }
class B {
fun A.newFunction() { ... }
}
But is there some way to create extension variable? Like:
class B {
var A.someCounter: Int = 0
}
You can create an extension property with overridden getter and setter:
var A.someProperty: Int
get() = /* return something */
set(value) { /* do something */ }
But you cannot create an extension property with a backing field because you cannot add a field to an existing class.
No - the documentation explains this:
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on instances of this class.
and
Note that, since extensions do not actually insert members into classes, there’s no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. Their behavior can only be defined by explicitly providing getters/setters.
Thinking about extension functions/properties as just syntactic sugar for calling a static function and passing in a value hopefully makes this clear.
However, if you really, really want to do something like this...
As stated above regarding efficiency, an additional backing field added directly to the class is the best way to store data non-derivable from existing non-private members from the class. However, if you don't control the implementation of the class and are dead-set on creating a new property that can store new data, it can be done in a way that is not abysmally inefficient by using separate external tables. Use a separate map that keys on object instances of this class with values that map directly to the value you want to add then define an extension getter and/or setter for this property which uses your external table to store the data associated with each instance.
val externalMap = mutableMapOf<ExistingClass, Int>()
var ExistingClass.newExtensionProperty : Int
get() = externalMap[this] ?: 0
set(value:Int) { externalMap[this] = value }
The additional map lookups will cost you - and you need to consider memory leaks, or using appropriately GC-aware types, but it does work.
There's no way to add extension properties with backing fields to classes, because extensions do not actually modify a class.
You can only define an extension property with custom getter (and setter for var) or a delegated property.
However, if you need to define an extension property which would behave as if it had a backing field, delegated properties come in handy.
The idea is to create a property delegate that would store the object-to-value mapping:
using the identity, not equals()/hashCode(), to actually store values for each object, like IdentityHashMap does;
not preventing the key objects from being garbage collected (using weak references), like WeakHashMap does.
Unfortunately, there is no WeakIdentityHashMap in JDK, so you have to implement your own (or take a complete implementation).
Then, based on this mapping you can create a delegate class satisfying the property delegates requirements. Here's an example non-thread-safe implementation:
class FieldProperty<R, T : Any>(
val initializer: (R) -> T = { throw IllegalStateException("Not initialized.") }
) {
private val map = WeakIdentityHashMap<R, T>()
operator fun getValue(thisRef: R, property: KProperty<*>): T =
map[thisRef] ?: setValue(thisRef, property, initializer(thisRef))
operator fun setValue(thisRef: R, property: KProperty<*>, value: T): T {
map[thisRef] = value
return value
}
}
Usage example:
var Int.tag: String by FieldProperty { "$it" }
fun main(args: Array<String>) {
val x = 0
println(x.tag) // 0
val z = 1
println(z.tag) // 1
x.tag = "my tag"
z.tag = x.tag
println(z.tag) // my tag
}
When defined inside a class, the mapping can be stored independently for instances of the class or in a shared delegate object:
private val bATag = FieldProperty<Int, String> { "$it" }
class B() {
var A.someCounter: Int by FieldProperty { 0 } // independent for each instance of B
var A.tag: String by bATag // shared between the instances, but usable only inside B
}
Also, please note that identity is not guaranteed for Java's primitive types due to boxing.
And I suspect the performance of this solution to be significantly worse than that of regular fields, most probably close to normal Map, but that needs further testing.
For nullable properties support and thread-safe implementation please refer to here.
You can't add a field, but you can add a property, that delegates to other properties/methods of the object to implement its accessor(s). For example suppose you want to add a secondsSinceEpoch property to the java.util.Date class, you can write
var Date.secondsSinceEpoch: Long
get() = this.time / 1000
set(value) {
this.time = value * 1000
}
If you are extending View you can do it quite easily like this...
This is example how I create some my custom class Event property in EditText class extension:
Define id for key :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="EditTextEventOnClearTagKey" type="id" />
</resources>
Define one reusable extension like this:
fun <T : Any> View.tagProperty(#IdRes key: Int, onCreate: () -> T): T {
#Suppress("UNCHECKED_CAST")
var value = getTag(key) as? T
if (value.isNull) {
value = onCreate()
setTag(key, value)
}
return value!!
}
Use it in wherever View extension you need:
val EditText.eventClear get() = tagProperty(R.id.EditTextEventOnClearTagKey) { event<Unit>() }

How to delegate implementation to a property in Kotlin?

Kotlin enables me to implement an interface by delegating to a primary constructor argument like so:
class Foo(xs : ArrayList<Int>) : List<Int> by xs { }
But this exhibits the backing implementer to the user. Delegating to an anonymous also seems to be ok:
class Foo() : List<Int> by ArrayList<Int>() { }
This hides the implementation details, but we loose access to features not provided by the interface, which in this case is mutability.
I would therefore like to delegate the implementation to a property that is not in the primary constructor. What I would like to have is similar to
class Foo() : List<Int> by xs {
val xs : List<Int> = ArrayList<Int>()
}
which doesn't compile.
Is it possible to have a property defined explicitly in the class body and still be able to delegate implementation to it?
This is not currently possible. The expression in the by-clause is computed only once before the construction of the class, so you cannot reference symbols of that class.
There is a request in the issue tracker to allow this, although it's almost definitely not going to be supported in Kotlin 1.0.
One funny workaround that sometimes works is to make the property which you want to be a delegate, a constructor parameter with the default value instead. That way it'll be accessible both in the by-clause and in the class body:
class Foo(val xs: List<Int> = ArrayList<Int>()) : List<Int> by xs {
fun bar() {
println(xs)
}
}
Keep in mind though that xs in by xs is still calculated only once here, so even if xs is a var property, only the default value provided in the constructor will be used. It's not a universal solution, but sometimes it can help.
Expanding on the answer of Alexander Udalov, I came up with a solution using a private base class
private open class FooBase(protected val xs : MutableList<Int>) : List<Int> by xs { }
class Foo() : FooBase(ArrayList()) {
fun bar() {
xs.add(5)
}
}
Now I can have access to the property backing my interface implementation but am not restricted to operations provided by that interface while still hiding the actual implementation from the user.
Note: Although it works, I get the following warning from IntelliJ IDEA 15 CE which arises from EXPOSED_SUPER_CLASS inspection: Deprecated: subclass effective visibility 'public' should be the same or less permissive than its superclass effective visibility 'private'. I'm not quite sure what the deprecated part here means – whether the warning will be removed in the future or this won't compile at some point. Anyway, we don't really have to use a private open class, abstract or simply open will do, because even if the user is allowed to create an instance of FooBase, there is not much he can do with it.
Update:
There is actualy a simple and compact solution that does not use any suspicious behaviour:
class Foo private constructor(private val xs: ArrayList<Int>) : List<Int> by xs {
constructor() : this(ArrayList<Int>()) { }
}