Is there an annotation that triggers a warning if an object is passed that captures enclosing ‘this’? - kotlin

I have a Kotlin function with this signature:
fun registerDisposer(obj: Any, disposer: Closeable)
What the function does is attach disposer to a phantom reference and arrange it to be closed when obj is garbage-collected (i.e. when the phantom reference object is enqueued). The class of obj is supposed to call it something like this:
class Holder(private val res1: Closeable, private val res2: Closeable) {
init {
registerDisposer(this, object: Closeable {
private val res1 = this#Holder.res1
private val res2 = this#Holder.res2
override fun close() {
res1.close()
res2.close()
}
})
}
}
(Let’s ignore whether this is a good idea to rely on this with general Closeables; the actual resource in question is a pointer managed by native/JNI code – I am trying to follow Hans Boehm’s advice. But all of this is not particularly relevant for this question.)
I am worried that this design makes it too easy to inadvertently pass an object that captures this from the outer scope, creating a reference loop and preventing the object from being garbage-collected at all:
registerDisposer(this, Closeable {
this.res1.close()
this.res2.close()
})
Is there an annotation I can add to the disposer parameter that will trigger a warning in this situation?

As of this writing, the answer seems to be: probably not.
It turns out a registerDisposer function already exists as the register method of java.lang.ref.Cleaner, and it has no such annotation.
In Android, there is a similar annotation for android.os.AsyncTask, but that simply warns at any anonymous object having AsyncTask as its base class, whether it captures this or not. (This makes sense in Java, where anonymous classes always capture this, but not in Kotlin.)

Related

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.

What private constructor in Kotlin for?

I'm a newbie in Kotlin. I want to ask what private constructor in Kotlin for? class DontCreateMe private constructor () { /*...*/ }. I mean what class is supposed to be if we can't create its instance?
Well, the answers in the comments are correct, but since nobody wrote a full answer. I'm going to have a go at it.
Having a private constructor does not necessarily mean that an object cannot be used by external code. It just means that the external code cannot directly use its constructors, so it has to get the instances through an exposed API in the class scope. Since this API is in the class scope, it has access to the private constructor.
The simplest example would be:
class ShyPerson private constructor() {
companion object {
fun goToParty() : ShyPerson {
return ShyPerson()
}
}
}
fun main(args: String) {
// outside code is not directly using the constructor
val person = ShyPerson.goToParty()
// Just so you can see that you have an instance allocated in memory
println(person)
}
The most common use case for this that I've seen is to implement the Singleton pattern, as stated by Mojtaba Haddadi, where the external code can only get access to one instance of the class.
A simple implementation would be:
class Unity private constructor() {
companion object {
private var INSTANCE : Unity? = null
// Note that the reason why I've returned nullable type here is
// because kotlin cannot smart-cast to a non-null type when dealing
// with mutable values (var), because it could have been set to null
// by another thread.
fun instance() : Unity? {
if (INSTANCE == null) {
INSTANCE = Unity()
}
return INSTANCE
}
}
}
fun main(args: Array<String>) {
val instance = Unity.instance()
println(instance)
}
This is often used so that classes that are resource consuming are only instantiated once or so that certain pieces of data are shared by the entire codebase.
Be aware that kotlin uses the object keyword to implement this pattern, with the advantage of being thread-safe. Also some developers consider Singletons to be an anti-pattern
Another use case for private constructors would be to implement Builder patterns, where classes that have complex initialization can be abstracted into a simpler API, so the user doesn't have to deal with clunky constructors. This other answer addresses its uses in kotlin.
One of the simplest uses in real life kotlin code that I've seen is on the Result implementation from the stdlib, where it's being used to change the internal representation of the object.

what actually param(this.otherParam) means in kotlin? [duplicate]

How is it related to extension functions? Why is with a function, not a keyword?
There appears to be no explicit documentation for this topic, only the assumption of knowledge in reference to extensions.
It is true that there appears to be little existing documentation for the concept of receivers (only a small side note related to extension functions), which is surprising given:
their existence springing out of extension functions;
their role in building a DSL using said extension functions;
the existence of a standard library function with, which given no knowledge of receivers might look like a keyword;
a completely separate syntax for function types.
All these topics have documentation, but nothing goes in-depth on receivers.
First:
What's a receiver?
Any block of code in Kotlin may have a type (or even multiple types) as a receiver, making functions and properties of the receiver available in that block of code without qualifying it.
Imagine a block of code like this:
{ toLong() }
Doesn't make much sense, right? In fact, assigning this to a function type of (Int) -> Long - where Int is the (only) parameter, and the return type is Long - would rightfully result in a compilation error. You can fix this by simply qualifying the function call with the implicit single parameter it. However, for DSL building, this will cause a bunch of issues:
Nested blocks of DSL will have their upper layers shadowed:
html { it.body { // how to access extensions of html here? } ... }
This may not cause issues for a HTML DSL, but may for other use cases.
It can litter the code with it calls, especially for lambdas that use their parameter (soon to be receiver) a lot.
This is where receivers come into play.
By assigning this block of code to a function type that has Int as a receiver (not as a parameter!), the code suddenly compiles:
val intToLong: Int.() -> Long = { toLong() }
Whats going on here?
A little side note
This topic assumes familiarity with function types, but a little side note for receivers is needed.
Function types can also have one receiver, by prefixing it with the type and a dot. Examples:
Int.() -> Long // taking an integer as receiver producing a long
String.(Long) -> String // taking a string as receiver and long as parameter producing a string
GUI.() -> Unit // taking an GUI and producing nothing
Such function types have their parameter list prefixed with the receiver type.
Resolving code with receivers
It is actually incredibly easy to understand how blocks of code with receivers are handled:
Imagine that, similar to extension functions, the block of code is evaluated inside the class of the receiver type. this effectively becomes amended by the receiver type.
For our earlier example, val intToLong: Int.() -> Long = { toLong() } , it effectively results in the block of code being evaluated in a different context, as if it was placed in a function inside Int. Here's a different example using handcrafted types that showcases this better:
class Bar
class Foo {
fun transformToBar(): Bar = TODO()
}
val myBlockOfCodeWithReceiverFoo: (Foo).() -> Bar = { transformToBar() }
effectively becomes (in the mind, not code wise - you cannot actually extend classes on the JVM):
class Bar
class Foo {
fun transformToBar(): Bar = TODO()
fun myBlockOfCode(): Bar { return transformToBar() }
}
val myBlockOfCodeWithReceiverFoo: (Foo) -> Bar = { it.myBlockOfCode() }
Notice how inside of a class, we don't need to use this to access transformToBar - the same thing happens in a block with a receiver.
It just so happens that the documentation on this also explains how to use an outermost receiver if the current block of code has two receivers, via a qualified this.
Wait, multiple receivers?
Yes. A block of code can have multiple receivers, but this currently has no expression in the type system. The only way to achieve this is via multiple higher-order functions that take a single receiver function type. Example:
class Foo
class Bar
fun Foo.functionInFoo(): Unit = TODO()
fun Bar.functionInBar(): Unit = TODO()
inline fun higherOrderFunctionTakingFoo(body: (Foo).() -> Unit) = body(Foo())
inline fun higherOrderFunctionTakingBar(body: (Bar).() -> Unit) = body(Bar())
fun example() {
higherOrderFunctionTakingFoo {
higherOrderFunctionTakingBar {
functionInFoo()
functionInBar()
}
}
}
Do note that if this feature of the Kotlin language seems inappropriate for your DSL, #DslMarker is your friend!
Conclusion
Why does all of this matter? With this knowledge:
you now understand why you can write toLong() in an extension function on a number, instead of having to reference the number somehow. Maybe your extension function shouldn't be an extension?
You can build a DSL for your favorite markup language, maybe help parsing the one or other (who needs regular expressions?!).
You understand why with, a standard library function and not a keyword, exists - the act of amending the scope of a block of code to save on redundant typing is so common, the language designers put it right in the standard library.
(maybe) you learned a bit about function types on the offshoot.
When you call:
"Hello, World!".length()
the string "Hello, World!" whose length you're trying to get is called the receiver.
More generally, any time you write someObject.someFunction(), with a . between the object and the function name, the object is acting as the receiver for the function. This isn't special to Kotlin, and is common to many programming languages that use objects. So the concept of a receiver is likely very familiar to you, even if you haven't heard the term before.
It's called a receiver because you can think of the function call as sending a request which the object will receive.
Not all functions have a receiver. For example, Kotlin's println() function is a top-level function. When you write:
println("Hello, World!")
you don't have to put any object (or .) before the function call. There's no receiver because the println() function doesn't live inside an object.
On the receiving end
Now let's look at what a function call looks like from the point of view of the receiver itself. Imagine we've written a class that displays a simple greeting message:
class Greeter(val name: String) {
fun displayGreeting() {
println("Hello, ${this.name}!")
}
}
To call displayGreeting(), we first create an instance of Greeter, then we can use that object as a receiver to call the function:
val aliceGreeter = Greeter("Alice")
val bobGreeter = Greeter("Bob")
aliceGreeter.displayGreeting() // prints "Hello, Alice!"
bobGreeter.displayGreeting() // prints "Hello, Bob!"
How does the displayGreeting function know which name to display each time? The answer is the keyword this, which always refers to the current receiver.
When we call aliceGreeter.displayGreeting(), the receiver is aliceGreeter, so this.name points to "Alice".
When we call bobGreeter.displayGreeting(), the receiver is bobGreeter, so this.name points to "Bob".
Implicit receivers
Most of the time, there's actually no need to write this. We can replace this.name with just name and it will implicitly point to the name property of the current receiver.
class Greeter(val name: String) {
fun displayGreeting() {
println("Hello, $name!")
}
}
Notice how that differs from accessing a property from outside the class. To print the name from outside, we'd have to write out the full name of the receiver:
println("Hello, ${aliceGreeter.name}")
By writing the function inside the class, we can omit the receiver completely, making the whole thing much shorter. The call to name still has a receiver, we just didn't have to write it out. We can say that we accessed the name property using an implicit receiver.
Member functions of a class often need to access many other functions and properties of their own class, so implicit receivers are very useful. They shorten the code and can make it easier to read and write.
How do receivers relate to extensions?
So far, it seems like a receiver is doing two things for us:
Sending a function call to a specific object, because the function lives inside that object
Allowing a function convenient and and concise access to the other properties and functions that live inside the same object
What if we want to write a function that can use an implicit receiver for convenient access to the properties and functions of an object, but we don't want to (or can't) write our new function inside that object/class? This is where Kotlin's extension functions come in.
fun Greeter.displayAnotherGreeting() {
println("Hello again, $name!")
}
This function doesn't live inside Greeter, but it accesses Greeter as if it was a receiver. Notice the receiver type before the function name, which tells us that this is an extension function. In the body of the extension function, we can once again access name without its receiver, even though we're not actually inside the Greeter class.
You could say that this isn't a "real" receiver, because we're not actually sending the function call to an object. The function lives outside the object. We're just using the syntax and appearance of a receiver because it makes for convenient and concise code. We can call this an extension receiver, to distinguish it from the dispatch receiver that exists for functions that are really inside an object.
Extension functions are called in the same way as member functions, with a receiver object before the function name.
val aliceGreeter = Greeter("Alice")
aliceGreeter.displayAnotherGreeting() // prints "Hello again, Alice!"
Because the function is always called with an object in the receiver position before the function name, it can access that object using the keyword this. Like a member function, an extension function can also leave out this and access the receiver's other properties and functions using the current receiver instance as the implicit receiver.
One of the main reasons extension functions are useful is that the current extension receiver instance can be used as an implicit receiver inside the body of the function.
What does with do?
So far we've seen two ways to make something available as an implicit receiver:
Create a function inside the receiver class
Create an extension function outside the class
Both approaches require creating a function. Can we have the convenience of an implicit receiver without declaring a new function at all?
The answer is to call with:
with(aliceGreeter) {
println("Hello again, $name!")
}
Inside the block body of the call to with(aliceGreeter) { ... }, aliceGreeter is available as an implicit receiver and we can once again access name without its receiver.
So how come with can be implemented as a function, rather than a language feature? How is it possible to simply take an object and magic it into an implicit receiver?
The answer lies with lambda functions. Let's consider our displayAnotherGreeting extension function again. We declared it as a function, but we could instead write it as a lambda:
val displayAnotherGreeting: Greeter.() -> Unit = {
println("Hello again, $name!")
}
We can still call aliceGreeter.displayAnotherGreeting() the same as before, and the code inside the function is the same, complete with implicit receiver. Our extension function has become a lambda with receiver. Note the way the Greeter.() -> Unit function type is written, with the extension receiver Greeter listed before the (empty) parameter list ().
Now, watch what happens when we pass this lambda function as an argument to another function:
fun runLambda(greeter: Greeter, lambda: Greeter.() -> Unit) {
greeter.lambda()
}
The first argument is the object that we want to use as the receiver. The second argument is the lambda function we want to run. All runLambda does is to call the provided lambda parameter, using the greeter parameter as the lambda's receiver.
Substituting the code from our displayAnotherGreeting lambda function into the second argument, we can call runLambda like this:
runLambda(aliceGreeter) {
println("Hello again, $name!")
}
And just like that, we've turned aliceGreeter into an implicit receiver. Kotlin's with function is simply a generic version of this that works with any type.
Recap
When you call someObject.someFunction(), someObject is acting as the receiver that receives the function call
Inside someFunction, someObject is "in scope" as the current receiver instance, and can be accessed as this
When a receiver is in scope, you can leave out the word this and access its properties and functions using an implicit receiver
Extension functions let you benefit from the receiver syntax and implicit receivers without actually dispatching a function call to an object
Kotlin's with function uses a lambda with receiver to make receivers available anywhere, not just inside member functions and extension functions
Kotlin knows the concept of a function literals with receiver. It enables access on visible methods and properties of a receiver of a lambda within its body without having to use any additional qualifier. That's very similar to extension functions in which you can as well access members of the receiver object inside the extension.
A simple example, also one of the greatest functions in the Kotlin standard library, is apply:
public inline fun <T> T.apply(block: T.() -> Unit): T {
block()
return this
}
Here, block is a function literal with receiver. This block parameter is executed by the function and the receiver of apply, T, is returned to the caller. In action this looks as follows:
val foo: Bar = Bar().apply {
color = RED
text = "Foo"
}
We instantiate an object of Bar and call apply on it. The instance of Bar becomes the receiver of apply. The block, passed as an argument in curly brackets does not need to use additional qualifiers to access and modify the properties color and text.
The concept of lambdas with receiver is also the most important feature for writing DSLs with Kotlin.
var greet: String.() -> Unit = { println("Hello $this") }
this defines a variable of type String.() -> Unit, which tells you
String is the receiver
() -> Unit is the function type
Like F. George mentioned above, all methods of this receiver can be called in the method body.
So, in our example, this is used to print the String. The function can be invoked by writing...
greet("Fitzgerald") // result is "Hello Fitzgerald"
the above code snippet was taken from Kotlin Function Literals with Receiver – Quick Introduction by Simon Wirtz.
Simply put ( without any extra words or complications) , the "Receiver" is the type being extended in the extension function or the class name. Using the examples given in answers above
fun Foo.functionInFoo(): Unit = TODO()
Type "Foo" is the "Receiver"
var greet: String.() -> Unit = { println("Hello $this") }
Type "String" is the "Receiver"
Additional tip: Look out for the Class before the fullstop(.) in the "fun" (function) declaration
fun receiver_class.function_name() {
//...
}
Simply put:
the receiver type is the type an extension function extends
the receiver object is the object an extension function is called on; the this keyword inside the function body corresponds to the receiver object
An extension function example:
// `Int` is the receiver type
// `this` is the receiver object
fun Int.squareDouble() = toLong() * this
// a receiver object `8` of type `Int` is passed to the `square` function
val result = 8.square()
A function literal example, which is pretty much the same:
// `Int` is the receiver type
// `this` is the receiver object
val square: Int.() -> Long = { toLong() * this }
// a receiver object `8` of type `Int` is passed to the `square` function
val result1 = 8.square()
val result2 = square(8) // this call is equal to the previous one
The object instance before the . is the receiver. This is in essence the "Scope" you will define this lambda within. This is all you need to know, really, because the functions and properties(varibles, companions e.t.c) you will be using in the lambda will be those provided within this scope.
class Music(){
var track:String=""
fun printTrack():Unit{
println(track)
}
}
//Music class is the receiver of this function, in other words, the lambda can be piled after a Music class just like its extension function Since Music is an instance, refer to it by 'this', refer to lambda parameters by 'it', like always
val track_name:Music.(String)->Unit={track=it;printTrack()}
/*Create an Instance of Music and immediately call its function received by the name 'track_name', and exclusively available to instances of this class*/
Music().track_name("Still Breathing")
//Output
Still Breathing
You define this variable with and all the parameters and return types it will have but among all the constructs defined, only the object instance can call the var, just like it would an extension function and supply to it its constructs, hence "receiving" it.
A receiver would hence be loosely defined as an object for which an extension function is defined using the idiomatic style of lambdas.
Typically in Java or Kotlin you have methods or functions with input parameters of type T. In Kotlin you can also have extension functions that receive a value of type T.
If you have a function that accepts a String parameter for example:
fun hasWhitespace(line: String): Boolean {
for (ch in line) if (ch.isWhitespace()) return true
return false
}
converting the parameter to a receiver (which you can do automatically with IntelliJ):
fun String.hasWhitespace(): Boolean {
for (ch in this) if (ch.isWhitespace()) return true
return false
}
we now have an extension function that receives a String and we can access the value with this

What is the benefit of having a private constructor and a use a method inside companion object to instantiate a class?

I've bumped into this code and I'm not sure why would anyone do this. Basically the author decided for making the class constructor private so that it cannot be instantiated outside the file, and added a public method to a companion object in the class that creates a new instance of this class. What is the benefit of this approach?
This is what I found:
class Foo private constructor(private val arg1: Any) {
//more code here..
companion object {
fun newFoo(arg1: Any) = Foo(arg1 = arg1)
}
}
Why is it better than this?
class Foo(private val arg1: Any) {
//more code here..
}
There are several benefits to providing a factory method instead of a public constructor, including:
It can do lots of processing before calling the construstor. (This can be important if the superclass constructor takes parameters that need to be calculated.)
It can return cached values instead of new instances where appropriate.
It can return a subclass. (This allows you to make the top class an interface, as noted in another answer.) The exact class can differ between calls, and can even be an anonymous type.
It can have a name (as noted in another answer). This is especially important if you need multiple methods taking the same parameters. (E.g. a Point object which could be constructed from rectangular or polar co-ordinates.) However, a factory method doesn't need a specific name; if you implement the invoke() method in the companion object, you can call it in exactly the same way as a constructor.
It makes it easier to change the implementation of the class without affecting its public interface.
It also has an important drawback:
It can't be used by subclass constructors.
Factory methods seem to be less used in Kotlin than Java, perhaps due to Kotlin's simpler syntax for primary constructors and properties. But they're still worth considering — especially as Kotlin companion objects can inherit.
For much deeper info, see this article, which looks at the recommendation in Effective Java and how it applies to Kotlin.
If you want to change Foo into an interface in the future the code based on the method will keep working, since you can return a concrete class which still implements Foo, unlike the constructor which no longer exists.
An example specific to android is, that Fragments should be constructed with an empty constructed, and any data you'd like to pass through to them should be put in a bundle.
We can create a static/companion function, which takes in the arguments we need for that fragment, and this method would construct the fragment using the empty constructor and pass in the data using a bundle.
There are many useful cases, for example what Kiskae described. Another good one would be to be able to "give your constructors names":
class Foo<S: Any, T: Any> private constructor(private val a: S, private val b: T) {
//more code here...
companion object {
fun <S: Any> createForPurposeX(a: S) = Foo(a = a, b = "Default value")
fun createForPurposeY() = Foo(a = 1, b = 2)
}
}
Call site:
Foo.createForPurposeX("Hey")
Foo.createForPurposeY()
Note: You should use generic types instead of Any.

Can extension functions be called in a "static" way?

Is it possible to create an extension function and call it as if it were static?
For Example...
fun System.sayByeAndExit() {
println("Goodbye!")
System.exit()
}
fun main(args: Array<String>) {
System.sayByeAndExit() // I'd like to be able to call this
}
I know that the code sample doesn't work...
I understand that kotlin's extension functions are resolved statically, as mentioned in the Kotlin Reference (Extension Functions), but this does not mean they can be called as if they were static functions within a class (in a Java sense).
I also understand that this code will not work because there is no instance of System to pass into the method that the compiler will generate; therefore it won't compile.
Why would I want this?
Some of you might be wondering why this behaviour is desirable. I can understand why you would think that is isn't, so here are some reasons:
It has all of the benefits that standard extension functions give.
An instance of the class doesn't need to be created just to access the extra functionality.
The functions can be accessed from an application-wide context (provided the class is visible).
To summarise...
Does Kotlin have a way to "hook" a static function onto a class? I'd love to know.
You are really asking for "extension functions for a Class reference" or "adding static methods to existing classes" which was covered by another question here: How can one add static methods to Java classes in Kotlin which is covered by a feature request KT-11968
Extension functions cannot be added to anything that does not have an instance. A reference to a Class is not an instance and therefore you cannot extend something like java.lang.System. You can however extend a companion object of an existing class. For example:
class LibraryThing {
companion object { /* ... */ }
}
Allows you to extend LibraryThing.Companion and therefore calling some new myExtension() method would look like you are extending the Class reference itself, when really you are extending the singleton instance of the companion object:
fun LibraryThing.Companion.myExtension() = "foo"
LibraryThing.Companion.myExtension() // results in "foo"
LibraryThing.myExtension() // results in "foo"
Therefore you might find some Kotlin libraries add empty companion objects just for this case. Others do not, and for those you are "out of luck." Since Java does not have companion objects, you cannot do the same for Java either.
The other commonly requested feature is to take an existing Java static method that accepts an instance of a class as the first parameter, and make it behave as an extension function. This is tracked by issues KT-5261, KT-2844, KT-732, KT-3487 and probably other feature requests.
You can define extension function for an object and use it from system-wide context. An object will be created only once.
object MyClz
fun MyClz.exit() = System.exit(0)
fun main(args: Array<String>) {
MyClz.exit()
}
Or
class MyClz {
companion object
}
fun MyClz.Companion.exit() = System.exit(0)
fun main(args: Array<String>) {
MyClz.exit()
}