Kotlin - delegate as function argument (anonymous instantiation) - kotlin

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 )

Related

Differenence between ways to declare functions in Kotlin

I have seen some code declaring functions as seen below. What is the difference between fun1 and fun2?
interface Test {
fun fun1() : Boolean = false
}
fun Test.fun2() : Boolean = true
fun1 defined inside the interface describes an open function that any implementer of the interface can override. Since it also defines a default implementation by returning something, it is not abstract and implementing classes can choose not to override it.
fun2 is an extension function. When these are used with interfaces, often the reason is to discourage overriding. An extension function cannot be overridden, but it can be hidden by another extension function with the same signature, but only in a specific scope. Therefore, some implementer of Test in another module that passes its instance back to this module cannot change the functionality of fun2 as used in this module.
The second version is an extension function.
The difference is that extension functions can be applied to any type (even outside of your code), but they do not have access to private members of that type. They are pretty much the same as calling function with this type as a first parameter, just nicer syntax

Reflection and Generics in Kotlin

I've written myself into a corner where I want an instance of Class<Foo<Bar>>. While there's no apparent reason that this shouldn't be valid, there seems to be no way to create one. Foo<Bar>::class.java is a syntax error, and Kotlin does not provide a public constructor for Class.
The code I'm writing is an abstraction layer over gson. Below is an overly-simplified example:
class Boxed<T : Any> (val value: T)
class BaseParser<U : Any> (
private val clazz: Class<U>
) {
//This works for 98% of cases
open fun parse(s: String): U {
return gson.fromJson(s, clazz)
}
//Presume that clazz is required for other omitted functions
}
//Typical subclass:
class FooParser : BaseParser<Foo>(Foo::class.java)
// Edge Case
class BarParser : BaseParser<Boxed<Bar>>(Boxed<Bar>::class.java) {
override fun parse(s: String): Boxed<Bar> {
return Boxed(gson.fromJson(s, Bar::class.java))
}
}
// not valid: "Only classes are allowed on the left hand side of a class literal"
In my production code, there are already dozens of subclasses that inherit from the base class, and many that override the "parse" function Ideally I'd like a solution that doesn't require refactoring the existing subclasses.
Actually, there is a reason this is impossible. Class (or Kotlin's KClass) can't hold parameterized types. They can hold e.g. List, but they can't List<String>. To store Foo<Bar> you need Type (or Kotlin's KType) and specifically ParameterizedType. These classes are somewhat more complicated to use and harder to acquire than simple Class.
The easiest way to acquire Type in Kotlin is by using its typeOf() utility:
typeOf<Foo<Bar>>().javaType
Gson supports both Class and Type, so you should be able to use it instead.
The closest you'll get is Boxed::class.java. This is not a language restriction but a JVM restriction. JVM has type erasure, so no generic types exist after compilation (thats also one of the reasons generics cant be primitives, as they need to be reference types to behave).
Does it work with the raw Boxed type class?
For this case, it looks like
BaseParser<Boxed<Bar>>(Boxed::class.java as Class<Boxed<Bar>>)
could work (that is, it will both type-check and succeed at runtime). But it depends on what exactly happens in the "Presume that clazz is required for other omitted functions" part. And obviously it doesn't allow actually distinguishing Boxed<Foo> and Boxed<Bar> classes.
I'd also consider broot's approach if possible, maybe by making BaseParser and new
class TypeBaseParser<U : Any>(private val tpe: Type)
extend a common abstract class/interface.

Property references vs. lambdas for getter/setter

I need to get and set a property of another class from a method and therefore need to pass in either the property reference of lambdas for the getter and the setter:
Passing in the property reference
otherInstance::property
Passing in a lambda for the getter and one for the setter:
{otherInstance.property} // getter
{value -> otherInstance.property = value} // setter
I like the first one, because for me the code is easier to read and shorter, but my alarm bells ring when I read about it on the official documentation, because of the term "reflection". My knowledge from Java is that reflection generally isn't a good thing. Is that also valid with Kotlin? Is it valid with this case? Is one of both ways (property reference or lambdas) more performant or more safe?
By using KMutableProperty0 you would technically be exposing an object that can be used for reflection. If you want to be strict about avoiding reflection, you could use the separate function references for the getter and setter. Note that it's not necessary to pass a lambda as a function reference to a higher-order function. The compiler can interpret property references as functions if the effective signature matches. This would unfortunately mean having to pass the property reference twice. Unfortunately, the setter has to be retrieved via what is technically reflection in this case:
class Test (var x: Int)
fun foo(getter: () -> Int, setter: (Int) -> Unit) {
//...
}
val test = Test(1)
foo(test::x, test::x.setter)
// Zero reflection call:
foo(test::x) { test.x = it }
At some point you have to question how badly you want to avoid reflection, because the above code looks very messy to me. If your class takes a KMutableProperty0 reference, it is much simpler to use. As long as your receiving function isn't using the reference to introspect the code, and only calls get() or set() on it, you are not really using reflection in the ways that are suggested should be avoided.
fun foo(property: KMutableProperty0<Int>) {
//...
}
val test = Test(1)
foo(test::x)
The documentation is about Member references and reflection,
If you are referring to Property references which isn't using reflection itself,
Reflection is only referred in different section Obtaining member references from a class reference
dynamically inspect an object to see e.g. what properties and functions it contains and which annotations exist on them. This is called reflection, and it's not very performant, so avoid it unless you really need it.
Kotlin has got its own reflection library (kotlin-reflect.jar must be included in your build). When targeting the JVM, you can also use the Java reflection facilities. Note that the Kotlin reflection isn't quite feature-complete yet - in particular, you can't use it to inspect built-in classes like String.

How to refer to yourself in the anonymous class?

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.

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.