How to refer to yourself in the anonymous class? - kotlin

I have next code in kotlin:
handler.postDelayed(object : Runnable {
override fun run() {
Timber.i("run post msg")
handler.postDelayed(this, AppPrefs.SEARCH_DELAY)
}
},AppPrefs.SOCKET_INTERVAL)
how you see it's simple standard way to create delayed task (with Runnable class). Value this references to anonimus Object implements Runnable and compile and works fine
But when i make lamdba for this:
handler.postDelayed({
Timber.i("run post msg")
handler.postDelayed(this, AppPrefs.SOCKET_INTERVAL)
},AppPrefs.SOCKET_INTERVAL)
value this referenced to outher class.
How referenced from inner anonimus class to yourself?

You cannot do this. A similar question was asked on Kotlin's forum and yole (one of the creators of the language) said this:
this in a lambda refers to the instance of the containing class, if any. A lambda is conceptually a function, not a class, so there is no such thing as a lambda instance to which this could refer.
The fact that a lambda can be converted into an instance of a SAM interface does not change this. Having this in a lambda mean different things depending on whether the lambda gets SAM-converted would be extremely confusing.

Related

Kotlin - delegate as function argument (anonymous instantiation)

Is it possible to create an anonymous delegate in Kotlin for the purpose of passing to a function argument? I'm particularly interested in by lazy, but this question probably applies to all delegates. For example, say I have this function:
fun sayHello(name: String){
println("Hello $name")
}
this works just fine:
val name by lazy{ "Ralph" }
sayHello(name)
But none of the following are correct:
sayHello(lazy{"Ralph"})
sayHello(by lazy{"Ralph"})
sayHello({"Ralph") as lazy})
Is this possible somehow?
There's not a practical way to do this for any general delegate. Delegates are designed for use specifically with properties, so their getter implementation takes an object instance (the property owner) and a KProperty argument (see ReadOnlyProperty). They might specifically need these references for their functionality.
The Lazy interface happens to have a value property so you can use it like this, but this does not apply to all delegates:
sayHello( lazy{"Ralph"}.value )

Utils class in Kotlin

In Java, we can create an utilities class like this:
final class Utils {
public static boolean foo() {
return false;
}
}
But how to do this in Kotlin?
I try using functions inside object:
object Utils {
fun foo(): Boolean {
return false
}
}
But when call this method from Java code it need to add INSTANCE. Ex: Utils.INSTANCE.foo().
Then I change to declare it as top-level function (without class or object):
#file:JvmName("Utils")
#file:JvmMultifileClass
fun foo(): Boolean {
return true
}
Then I can call Utils.foo() from Java code. But from Kotlin code I got Unresolved reference compiler error. It only allow be to use foo() function directly (without Utils prefix).
So what is the best approach for declaring utils class in Kotlin?
The last solution you've proposed is actually quite idiomatic in Kotlin - there's no need to scope your function inside anything, top level functions are just fine to use for utilities, in fact, that's what most of the standard library consists of.
You've used the #JvmName annotation the right way too, that's exactly how you're supposed to make these top level functions easily callable for Java users.
Note that you only need #JvmMultifileClass if you are putting your top level functions in different files but still want them to end up grouped in the same class file (again, only for Java users). If you only have one file, or you're giving different names per file, you don't need this annotation.
If for some reason you want the same Utils.foo() syntax in both Java and Kotlin, the solution with an object and then #JvmStatic per method is the way to do that, as already shown by #marianosimone in this answer.
You'd need to use #JvmStatic for that:
In Kotlin:
object Utils {
#JvmStatic
fun foo(): Boolean = true
}
val test = Utils.foo()
In Java:
final boolean test = Utils.foo()
Note that the util class you used in Java was the only way to supply additional functions there, for anything that did not belong to a particular type or object. Using object for that in Kotlin does not make any sense. It isn't a singleton, right?
The second approach you mentioned is rather the way to go for utility functions. Internally such functions get translated to static ones and as you can see they become the static util classes in Java you are searching for, as you can't have standalone functions in Java without a class or enum. In Kotlin itself however they are just functions.
Some even count utility classes to the anti-patterns. Functions on the other hand make totally sense without a class or object whose name hasn't so much meaning anyway.

Kotlin extension functions vs member functions?

I am aware that extension functions are used in Kotlin to extend the functionality of a class (for example, one from a library or API).
However, is there any advantage, in terms of code readability/structure, by using extension functions:
class Foo { ... }
fun Foo.bar() {
// Some stuff
}
As opposed to member functions:
class Foo {
...
fun bar() {
// Some stuff
}
}
?
Is there a recommended practice?
When to use member functions
You should use member functions if all of the following apply:
The code is written originally in Kotlin
You can modify the code
The method makes sense to be able to use from any other code
When to use extension functions
You should use extension functions if any of the following apply:
The code was originally written in Java and you want to add methods written in Kotlin
You cannot change the original code
You want a special function that only makes sense for a particular part of the code
Why?
Generally, member functions are easier to find than extension functions, as they are guaranteed to be in the class they are a member of (or a super class/interface).
They also do not need to be imported into all of the code that uses them.
From my point of view, there are two compelling reasons to use extension functions:
To "extend" the behaviour of a class you're not the author of / can't change (and where inheritance doesn't make sense or isn't possible).
To provide a scope for particular functionality. For example, an extension function may be declared as a freestanding function, in which case it's usable everywhere. Or you may choose to declare it as a (private) member function of another class, in which case it's only usable from inside that class.
It sounds like #1 isn't a concern in your case, so it's really more down to #2.
Extension functions are similar to those you create as a utility functions.
A basic example would be something like this:
// Strings.kt
fun String.isEmail() : Boolean {
// check for email pattern and return true/false
}
This code can be written as a utility function in Java like this:
class StringUtils {
public static boolean isEmail(String email) {
// check for email pattern and return true/false
}
}
So what it essentially does is, calling the same function with the object you call on will be passed as the first parameter to the argument. Like the same function I have given example of in Java.
If you want to call the extension function created in kotlin from java, you need to pass the caller as the first argument. Like,
StringsKt.isEmail("example#example.com")
As per the documentation,
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 variables of this type.
They are simply static functions with the caller as the first argument and other parameters followed by it. It just extends the ability for us to write it that way.
When to create extension functions?
When you don't have access to that class. When that class belongs to some library you have not created.
For primitive types. Int, Float, String, etc.
The another reason for using extension function is, you don't have to extend that class in order to use the methods, as if they belong to that class (but not actually part of that class).
Hope it makes a bit clear for you..
As mentioned in other answers, extension functions are primarily used in code that you can't change - maybe you want to change complex expression around some library object into easier and more readable expression.
My take would be to use extension functions for data classes. My reasoning is purely philosophical, data classes should be used only as data carriers, they shouldn't carry state and by themselves shouldn't do anything. That's why I think you should use extension function in case you need to write a function around data class.

Android Kotlin Extension super calling

i am a Java Android Developer and i'm approaching to Kotlin
I have defined the following class:
open class Player : RealmObject() {
...
}
And i defined the following two extensions, one for the generic RealmObject class and one for the specific Player class:
fun RealmObject.store() {
Realm.getDefaultInstance().use { realm ->
realm.beginTransaction()
realm.copyToRealmOrUpdate(this)
realm.commitTransaction()
}
}
fun Player.store(){
this.loggedAt = Date()
(this as RealmObject).store()
}
What i want is if i call .store() on any RealmObject object, the RelamObject.store() extension will be called BUT if i call .store() on a Player instance the extension that will be called will be Player.store().
(No problem for now)
I don't want to copy paste the same code, i love to write less reuse more.
So i need that internally the Player.store() will call the generic RealmObject.store()
I got it. The code i wrote up there is actually working as expected :D
What i am asking is (just because i wrote that just by personally intuition):
Is this the good way?! Or there is some better way?
Thank you
Your approach seems to be perfectly correct, because it does exactly what is needed. Kotlin resolves the extension calls based on the static (inferred or declared) type of the receiver expression, and the cast (this as RealmObject) makes the static expression type RealmObject.
Another valid way to do this, which I'm not sure is better, is to use a callable reference to the other extension:
fun Player.store(){
this.loggedAt = Date()
(RealmObject::store)(this)
}

when to use/make companion object?

So I'm new to Scala (and have almost zero java experience). I thought I understood OOP, in abstract, but disregard that. My question -- in a similar vein to "method name qualification when using a companion object" -- is about when a Scala pro would think to implement a class - companion object pattern?
From the question referenced above, it's not clear that companion objects were intended to store methods for the class's "internal use" (e.g. the poster wanted to use ^, defined in the object, inside /, defined in the class). So, I don't want to think of companion objects as "containers" for methods the companion class can use, because that's clearly not true...
I'm sorry if this is a vague question: I just want to know the correct way to use these guys.
Companion objects are useful for what you would use static methods for in Java...
One very common use is to define an apply() method in the companion object, which gives users the ability to use MyObject(arg, arg) as shorthand for new MyObject(arg, arg).
Companion objects are also a good place to put things like implicit defs.
I recently have been using companion objects in my akka apps as places to put message case classes which are specific to a supervisor actor and its children, but that I don't necessarily want code outside that subsystem to use directly.
Here's a simple example:
class Complex(real:Double, imag:Double) {
def +(that:Complex):Complex = Complex(this.real + that.real, this.imag + that.imag)
// other useful methods
}
// the companion object
object Complex {
def apply(real:Double, imag:Double) = new Complex(real, imag)
val i = Complex(0, 1)
implicit def fromInt(i:Int) = Complex(i, 0)
}
The normal OOP way to instantiate a new Complex object would be new Complex(x, i). In my companion object, I defined the function apply, to give us a syntactic sugar that allows us to write Complex(x, i). apply is a special function name which is invoked whenever you call an object directly as if it were a function (i.e., Complex()).
I also have a value called i which evaluates to Complex(0, 1), which gives me a shorthand for using the common complex number i.
This could be accomplished in Java using a static method like:
public static Complex i() {
return new Complex(0, 1);
}
The companion object essentially gives you a namespace attached to your class name which is not specific to a particular instance of your class.