what does mean javaClass in Kotlin? - kotlin

I see usage of reflection with
private fun invokeMethod(parameterTypes: Array<Class<*>>?, parameters: Array<Any>?, methodName: String?): Card? {
try {
//val method = javaClass.getDeclaredMethod(methodName, parameterTypes)
for (x in parameterTypes!!) println("Parameter Types: $x")
if (parameters != null) {
for (x in parameters) print("Parameters: $x")
}
val method = javaClass.getDeclaredMethod(methodName, *parameterTypes)
return method.invoke(this, parameters) as Card
} catch (e: Exception) {
println("Class Error ${e.message}")
}
return null
}
That is kotlin by the way,
Here is
val method = javaClass.getDeclaredMethod(methodName, *parameterTypes)
the method calling from
javaClass
I know we can call the method like this
Test obj = new Test();
Class cls = obj.getClass();
cls.getDeclaredMethod("method2", int.class)
So my question is which class does javaClass refer to?

It's an extension property on any non-nullable type. Here it's applied to this, which can be omitted as usual. So it will return the Class object for the instance it's called on, equivalent to this::class.java (which may be the same as the class the method defined in, or its subclass).

Related

Kotlin class generic type infered as nullable

A generic class for holding network request result
sealed class Result<out T : Any?> {
data class Success<out T : Any?>(val data: T) : Result<T>()
data class Error(val message: String, val exception: Exception? = null) : Result<Nothing>()
}
A generic function for encapsulating network result into Result.
It is called from a repository and passes a retrofit2 api call as an input parameter
suspend fun <T: Any?> request(method: Call<T>): Result<T> {
return withContext(Dispatchers.IO) {
try {
val response = method.awaitResponse() // Retrofit2 Call
if (response.isSuccessful)
Result.Success(response.body())
else
response.getErrorResult()
} catch (e: Exception) {
Result.Error(e.message.orEmpty(), e)
}
}
// Type mismatch.
// Required: Result<T>
// Found: Result<T?>
}
It is called like this
interface Webservice {
#GET("data")
fun getData(): Call<Data> // Retrofit2
}
suspend fun getData(): Result<Data> {
return request(webservice.getData())
}
Why does it infer the result as type T? but not T?
The problem is this line:
Result.Success(response.body())
body is marked with Nullable, so when ported to Kotlin, response.body() returns a T?, rather than T. See here for how this works.
Therefore, the type parameter for Result.Success is inferred to be T?, and so the expression above creates a Result<T?>. Note that the T in Result<T?> refers to the type parameter of request.

How do I make a delegate apply to all properties in a class?

I have a class, A, that needs to be marked as dirty anytime one of its properties is changed.
After reviewing the Kotlin docs, I know I need a delegate. So far I have:
abstract class CanBeDirty {
var isDirty = false
}
class A(
// properties getting set in constructor here
) : CanBeDirty {
var property1: String by DirtyDelegate()
var property2: Int by DirtyDelegate()
var property3: CustomObject by DirtyDelegate()
}
class DirtyDelegate() {
operator fun getValue(thisRef: CanBeDirty, property: KProperty<*>): Resource {
return valueOfTheProperty
}
operator fun setValue(thisRef: CanBeDirty, property: KProperty<*>, value: Any?) {
if (property != value) {
thisRef.isDirty = true
//set the value
}
else {
//don't set the value
}
}
}
I believe the lack of setting has something to do with vetoable() but the examples I see in Kotlin documentation don't really show me how to do this with a fully formed class Delegate (and I'm just not that up to speed on Kotlin syntax, honestly).
Your delegate class needs its own property to store the value it will return. And if you don't want to deal with uninitialized values, it should also have a constructor parameter for the initial value. You don't have to implement ReadWriteProperty, but it allows the IDE to autogenerate the correct signature for the two operator functions.
class DirtyDelegate<T>(initialValue: T): ReadWriteProperty<CanBeDirty, T> {
private var _value = initialValue
override fun getValue(thisRef: CanBeDirty, property: KProperty<*>): T {
return _value
}
override fun setValue(thisRef: CanBeDirty, property: KProperty<*>, value: T) {
if (_value != value) {
_value = value
thisRef.isDirty = true
}
}
}
Since this takes an initial value parameter, you have to pass it to the constructor:
class A: CanBeDirty() {
var property1: String by DirtyDelegate("")
var property2: Int by DirtyDelegate(0)
var property3: CustomObject by DirtyDelegate(CustomObject())
}
If you wanted to set an initial value based on something passed to the constructor, you could do:
class B(initialName: String): CanBeDirty() {
var name by DirtyDelegate(initialName)
}

Clean way to access outer class by the implementing delegate class

I was thinking about such case (accessing outer class which uses current class to implement some stuff):
interface Does {
fun doStuff()
}
class ReallyDoes: Does {
var whoShouldReallyDo: Does? = null
override fun doStuff() {
println("Doing stuff instead of $whoShouldReallyDo")
}
}
class MakesOtherDo private constructor(other: Does, hax: Int = 42): Does by other {
constructor(other: ReallyDoes): this(other.also { it.whoShouldReallyDo = this }, 42)
}
fun main(args: Array<String>) {
val worker = ReallyDoes()
val boss = MakesOtherDo(other = worker)
boss.doStuff()
}
Expected output:
Doing stuff instead of MakesOtherDo#28a418fc
But can't do that, because of error:
Error:(15, 79) Cannot access '' before superclass constructor
has been called
Which targets this statement: other.also { it.whoShouldReallyDo = this }
How can I (if at all) fix above implementation?
The reason for the error is other.also { ... = this } expression accesses this of type MakeOtherDo and is also used as argument to MakeOtherDo constructor. Hence, this will be accessed as part of MakeOtherDo (unary) constructor before this has been initialized as an instance of Does (super)class.
Since the assignment does not affect the initialization of the super class, you can executed it in the constructor of MakesOtherDo after the super class has been initialized.
class MakesOtherDo private constructor(other: Does, hax: Int = 42): Does by other {
constructor(other: ReallyDoes): this(other, 42) {
other.also { it.whoShouldReallyDo = this }
}
}
It took me a few minutes to decipher what you were doing above, and really the problem has nothing to do with delegates. You can simplify it down to this:
class Wrapper(var any: Any? = null)
class Test(val wrapper: Wrapper) {
constructor(): this(Wrapper(this)) // Cannot access "<this>" before superclass constructor has been called
}
The concept of "this" doesn't exist yet when we're still generating arguments for its constructor. You just need to move the assignment into the block of the constructor, which is code that's run after this becomes available:
class Test(val wrapper: Wrapper) {
constructor(): this(Wrapper()){
wrapper.any = this
}
}
Or in the case of your example:
constructor(other: ReallyDoes): this(other, 42){
other.whoShouldReallyDo = this
}

"Property must be initialized or be abstract" in init block when throwing an exception

Why does kotlin report Property must be initialized or be abstract. The object construction is never finished, so it should not matter whether a is initialized or not. Could a case be demonstrated where this would be a problem?
class Foo {
private val a: Int
init {
a = 42
throw Exception()
}
}
fun main() {
Foo()
}
kotlin playground
However these work just fine
fun bar() {
throw Exception()
}
class Foo {
private val a: Int
init {
a = 42
bar()
}
}
fun main() {
Foo()
}
kotlin playground
class Foo {
private val a: Int = throw Exception()
}
fun main() {
Foo()
}
kotlin playground
Similar java code works as expected:
public class Test {
private static class Foo {
private final int a;
public Foo() throws Exception {
a = 42;
throw new Exception();
}
}
public static void main(String []args) throws Exception {
new Foo();
}
}
The question is very well answered in the below link.
Kotlin: why do I need to initialize a var with custom getter?
Essentially it boils down to having a backing field for every "val" (property) . If you can provide a backing field, you need not initialize the field. Below is a small example of it.
class Foo {
private val a: Int
get() = getValue()
}
fun getValue():Int {
throw Exception()
}
fun main() {
Foo()
}
Similar java code works as expected:
Java initializes fields to 0 (or null/false depending on type) by default. You can see it e.g. by printing a's value before the a = 42 line.
Kotlin doesn't, because this implicit initialization makes it too easy to forget to initialize a property and doesn't provide much benefit. So it requires you to initialize all properties which have backing fields.
It seems to be a compiler bug as Alexey suggested
There is similar issue posted on Kotlin bug tracer.

kotlin function default arguments from java

given following Kotlin class:
class Foo {
public fun bar(i: Int = 0): Int = 2 * i
}
How should I call 'bar' function without any parameter from a java/groovy code?
def f = new Foo()
f.bar() //throws: java.lang.IllegalArgumentException: Parameter specified as non-null contains null
You can do this now in Kotlin. For your class method, use the #JvmOverloads annotation.
class Foo {
#JvmOverloads public fun bar(name: String = "World"): String = "Hello $name!"
}
Now simply call it from Java:
Foo foo = new Foo();
System.out.println(foo.bar());
System.out.println(foo.bar("Frank"));
Outputs the following:
Hello World!
Hello Frank!
I'll post the real answer shortly, but if anyone is wanting to do this from reflection, here is how the code would look. Much more complicated, but educational about how to use Kotlin reflection for KCallable.
Here is the class to call:
class Foo {
public fun bar(name: String = "World"): String = "Hello $name!"
}
Then we need a utility class in Kotin that can receive an instance of a class, a method from java reflection, and the parameters by name. This only works with non-primitives:
class KReflectHelper {
companion object {
#Suppress("UNCHECKED_CAST")
#JvmStatic fun <T> callKotlinMethodWithNamedParms(instance: Any, method: Method, parmMap: Map<String, Any>): T {
val callable: KFunction<T> = method.kotlinFunction as? KFunction<T> ?: throw IllegalStateException("Method is not a Kotlin method")
val unusedParms = HashSet(parmMap.keys)
val callableParms = hashMapOf<KParameter, Any?>()
callable.parameters.map { parm ->
if (parm.kind == KParameter.Kind.INSTANCE) {
callableParms.put(parm, instance)
} else if (parm.kind == KParameter.Kind.VALUE && parmMap.contains(parm.name)) {
unusedParms.remove(parm.name)
callableParms.put(parm, parmMap.get(parm.name))
} else if (parm.kind == KParameter.Kind.VALUE) {
if (parm.isOptional) {
// default value will be used!
} else {
throw IllegalStateException("Missing required parameter ${parm.name}")
}
} else {
throw IllegalStateException("Cannot call methods that are not direct instance methods")
}
}
if (unusedParms.isNotEmpty()) {
throw IllegalStateException("Unrecognized parameters passed to function: $unusedParms")
}
return method.kotlinFunction?.callBy(callableParms) as T
}
}
}
Now that static method can be called from Java, but it isn't so much fun. A code generator would really be required. Calling it from Kotlin is much easier and some frameworks (such as Klutter and Kovert) already use something along these lines.
Foo foo = new Foo();
System.out.println(foo.bar("Frank"));
Method barMethod = Foo.class.getMethod("bar", String.class);
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("name", "David");
System.out.println(KReflectHelper.callKotlinMethodWithNamedParms(foo, barMethod, parms));
// now call using the default
parms.clear();
System.out.println(KReflectHelper.callKotlinMethodWithNamedParms(foo, barMethod, parms));
Ouput:
Hello Frank!
Hello David!
Hello World!