Why the type of expression objectOfTypeT::class is KClass<out T>? - kotlin

Suppose we have generic function:
fun <T: Any> foo(o: T) {
o::class
}
The o::class's type is KClass<out T>. Why there is the out variance annotation, and why is it not KClass<out Any> (because T's erasure is Any)
This out variance annotation screwed my nice reflection code
EDIT:
After digging a while, I found kotlin rely on Object::getClass to get a Class to create a KClass, the actual creation code has a signature like fun <T: Any> create(jClass: Class<T>): KClass<T>. However this leads to another problem. The o::class should be of type KClass<Any> because jClass parameter of that create method should be of type Class<Object>, since the erasure of static type T is just Any (or Object, to which is mapped on JVM).

Why there is the out variance annotation?
This is expected behavior of the Bounded Class Reference in kotlin 1.1.
We know an instance of subclass can be assign to a supperclass, for example:
val long:Number = 1L;
val int:Number = 1;
We also know generic inheritance is not like class inheritance, for example:
val long:KClass<Long> = Long::class;
val number:KClass<Number> = long;
// ^
// can't be compiled, required KClass<Number> but found KClass<Number>
So we makes the code to be compiled by using Generic Type Projection as below:
val number:KClass<out Number> = long;
In Short, an variable of supperclass (Number) can be assign to an instances of any its subclasses (Long, Int, Double and .etc), but when get the KClass reference from the Number reference it should be return a KClass<out Number> rather than KClass<Number>, because KClass<Int> is not a subtype of the KClass<Number>.
The same rule applies in java, for example:
Number number = 1L;
Class<? extends Number> type = number.getClass();
Why is it not KClass (because T's erasure is Any)?
Because your method uses generic parameter T, but java.lang.Object#getClass don't uses any generic parameter at all and its return type is Class<? extends Object>.
However, the T#javaClass property takes a generic parameter T and you can see the code below that kotin cast a Class<?> to a Class<T>. so the Upper Bounded Wildcard of the o::class in the foo method is KClass<? extends T> rather than KClass<? extends Object> in java.
public inline val <T: Any> T.javaClass : Class<T>
#Suppress("UsePropertyAccessSyntax")
get() = (this as java.lang.Object).getClass() as Class<T>
// force to casting a Class<?> to a Class<T> ---^
A KClass<? extends T> is a subtype of KClass<?>, according to LISP principle you can't assign a superclass instance to a subclass type.
fun <T : Any> foo(value: T) {
val type: Class<out T> = (value as java.lang.Object).getClass();
// ^
// Compilation Error:
// you can't assign Class<? extends Object> to a Class<? extends T>
}
you can also see the method generic signature as below:
val noneGenericParametersMethod= Object::class.java.getDeclaredMethod("getClass")!!
val genericParametersMethod by lazy {
val it = object {
fun <T : Any> foo(): Class<out T> = TODO();
};
return#lazy it.javaClass.getDeclaredMethod("foo")!!;
}
println(genericParametersMethod.toGenericString())
// ^--- its return type is java.lang.Class<? extends T>
println(noneGenericParametersMethod.toGenericString())
// ^--- its return type is java.lang.Class<? extends Object>
Base on the above, the expression o::class actually returns a Raw Type KClass rather than a parameterized type KClass<out T>, and a Raw Type can be assign to any Parameterized Type, However, kotlin has no Raw Type, so kotlin compiler narrow the raw type KClass into the parameterized type KClass<out T>, just like as narrow an List<*> to an Iterable<*>. an example of Raw Type in java:
Box rawBox = new Box(); // rawBox is a raw type of Box<T>
Box<Integer> intBox = rawBox; // warning: unchecked conversion
Why java can't assign T.getClass() into a Class<? extends T>?
If you get deep into the documentation of the java.lang.Object#getClass method, you will found the result as below:
The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called.
"The erasure of the static type": which means |X| is the bounded type rather than the actual generic argument type in runtime, for example:
// Object.getClass() using the bounded static type `Number`
// v
<T extends Number> Class<? extends Number> foo(T value){
return value.getClass();
}

Related

Cloning object of subclass type in Kotlin

I wanted to be able to define a method to clone an object that is the same type of itself. I define the interface requesting such, but the following does not compile or run.
interface Foo {
fun <T: Foo> copy() : T
}
class Bar(private val v:Int) : Foo {
override fun copy():Bar = Bar(v)
}
main() {
val bar1 = Bar(1)
val bar2 = bar1.copy()
}
If however I write the implementing class in Java, it will compile
class Bar implements Foo {
private int v;
public Bar(int v) {this.v = v;}
public Bar copy() {
return new Bar(v);
}
}
I can rewrite the code like the following that compiles:
interface Foo<out Foo>{
fun copy(): Foo
}
class Bar(private val v:Int) : Foo<Bar> {
override fun copy(): Bar = Bar(v)
}
However the following will fail with error: no type arguments expected for fun copy(): Foo
val newF = f.copy()
fun <T: Foo> addFoo(
foo: T,
fooList: List<T>,
): MutableList<T> {
val result: MutableList<T> = arrayListOf()
for (f in fooList) {
val newF = f.copy<T>()
result.add(newF)
}
result.add(foo)
return result
}
Is there a good solution to the problem?
The problem here is that Foo doesn't know the exact type of the implementing class, so has no way to specify that its method returns that same type.
Unfortunately, Kotlin doesn't have self types (see this discussion), as they would handle this situation perfectly.
However, you can get close enough by using what C++ calls the curiously-recurring template pattern. In Kotlin (and Java) you do this by defining Foo with a type parameter explicitly extending itself (including its own type parameter):
interface Foo<T : Foo<T>> {
fun copy(): T
}
Then the implementing class can specify itself as the type argument:
class Bar(private val v: Int) : Foo<Bar> {
override fun copy(): Bar = Bar(v)
}
And because T is now the correct type, everything else works out. (In fact, the : Bar is redundant there, because it already knows what the type must be.)
Your addFoo() method will then compile with only a couple of changes: give it the same type parameter <T: Foo<T>>, and remove the (now wrong, but unnecessary) type parameter when calling f.copy(). A quick test suggests it does exactly what you want (creates a list with clones of fooList followed by foo).
Since it's often useful for a superclass or interface to refer to the implementing class, this pattern crops up quite often.
BTW, your code is easier to test if Bar has its own toString() implementation, as you can then simply print the returned list. You could make it a data class, or you could write your own, e.g.:
override fun toString() = "Bar($v)"

Default value for generic member

I'm trying this:
class Foo<T> {
var member: T = T()
}
...but the Kotlin compiler gives me an error: Type parameter T cannot be called as function.
How do I default-construct a generic member variable?
Well, to access the type information, we need to use the reified keyword on the type, but this is only applicable in inlined functions. So instead of relying on direct construction, a workaround can be to use a generator function wrapped in the companion object that immediately sets the member right after construction
// Test class to verify the implementation
class Yolo {
override fun toString() = "Yolo swag"
}
class Foo<T : Any> {
lateinit var member: T
companion object {
inline fun <reified T : Any> newInstance() =
T::class.java.newInstance().let { memberInstance ->
Foo<T>().apply { member = memberInstance}
}
}
}
fun main() {
// generate a Foo<Yolo>
val foo = Foo.newInstance<Yolo>()
println(foo.member) // displays "Yolo swag"
}
It's implied that T has a public no-arg constructor, but in general case it may not be true. This code uses reflection to bypass compiler complains about it (which may end up with runtime error if you dissapoint the JVM expectations and indeed pass T without public no-arg constructor).
//Reified generics at class level are not yet supported in Kotlin (KT-33213),
// so you have to pass instance of `KClass` manually as a consructor parameter
class Foo<T : Any>(clazz: KClass<T>) {
var member: T = clazz.createInstance()
}

Can we implement Rust like Traits using Kotlin Interfaces

Can we implement Rust like Traits and generic Traits using Kotlin Interfaces?
Also is there any way of using fn(&self) like construct in Kotlin class/interface default function implementations?
Can some examples be shown please?
Thanks
I don't know much about Rust, I'm referrring to these two videos as for what you're talking about, generic traits and &self explaination.
In kotlin you'd implement them using interfaces and classes as you've guessed.
An example of that is:
interface GenericTrait { // Same as traits
// <T:Any> just makes method to be called for non-null values, if you use <T>, you can pass null as well
fun <T: Any> method(value: T)
}
class TraitImpl : GenericTrait { // Same as structs
val isDisabled = Random.nextBoolean() // instance variable
// you can access instance parameter using the this or even not using it at all as in below
override fun <T: Any> method(value: T) {
println("Type of value is ${value::class}, and the value is $value. I am $isDisabled")
// or explicitly call ${this.isDisabled}, both are the same
}
}
fun main() {
TraitImpl().method("Hello")
TraitImpl().method(23)
TraitImpl().apply { // this: TraitImpl
method(23)
method(Unit)
}
}
Result:
Type of value is class kotlin.String, and the value is Hello. I am true
Type of value is class kotlin.Int, and the value is 23. I am true
Type of value is class kotlin.Int, and the value is 23. I am false
Type of value is class kotlin.Unit, and the value is kotlin.Unit. I am false
You can extract implementation outside if you want as an extension function just like you do in Rust.
interface GenericTrait {
val isDisabled: Boolean
}
class TraitImpl : GenericTrait {
override val isDisabled = Random.nextBoolean()
}
// define methods out of class declaration
fun <T: Any> GenericTrait.method(value: T) {
println("Type of value is ${value::class}, and the value is $value. I am $isDisabled")
}

why the translated kotlin code complains about a Array<BaseData>? to be a Array<out BaseData>

Having a java class, using androidStudio to translate to kotlin.
Got a error and not sure how to correctly translate it.
The java code:
public class BaseDataImpl extends BaseData {
private final BaseData[] translators;
public BaseDataImpl(final BaseData... translators) {
this.translators = cloneArray(translators);
}
public static <T> T[] cloneArray(final T[] array) {
if (array == null) {
return null;
}
return array.clone();
}
}
after the code translation, got error: required Array<BaseData>?, found Array<out BaseData>, but the translators in the cloneArray<BaseData>(translators) call is defined as val translators: Array<BaseData>?,
anyone could help to explain?
class BaseDataImpl(vararg translators: BaseData) : BaseData() {
private val translators: Array<BaseData>?
init {
this.translators = cloneArray<BaseData>(translators) //<=== error: required Array<BaseData>?, found Array<out BaseData>
}
companion object {
fun <T> cloneArray(array: Array<T>?): Array<T>? {
return array?.clone()
}
}
}
It is written in the Kotlin function reference regarding varargs:
Inside a function a vararg-parameter of type T is visible as an array of T, i.e. the ts variable in the example above has type Array<out T>.
where the referenced function was:
function <T> asList(vararg ts: T): List<T>
So in your case you actually pass an Array<out BaseData> but you only accept an array of type Array<T>? (in your case Array<BaseData>). Either you adapt all of the types to Array<out T> (which basically is similar as saying List<? extends BaseData> in Java) or you take care that you are only dealing with Ts instead, e.g. with:
inline fun <reified T> cloneArray(array: Array<out T>?): Array<T>? {
return array?.clone()?.map { it }?.toTypedArray()
}
But look up the documentation regarding this: Kotlin generics reference - type projections. You probably can accomplish this even easier.

Declaration-site variance may cause ClassCastException

Kotlin introduces Declaration-site variance described at here.
The out/in keywords for generic parameters may cause ClassCastException in some case. My program is shown below.
fun main(args: Array<String>) {
var l: List<String> = mutableListOf("string")
demo(l)
println("======")
for (s in l) {
println(s)
}
}
fun demo(strs: List<String>) {
val objects: List<Any> = strs // This is OK, since T is an out-parameter
if (objects is MutableList) {
val obs: MutableList<Any> = objects as MutableList<Any>
obs.add(TextView())
}
}
Output:
Exception in thread "main" java.lang.ClassCastException: com.kotlin.demo.clzz.TextView cannot be cast to java.lang.String
at com.kotlin.demo.clzz.Declaration_Site_VarianceKt.main(Declaration-Site-Variance.kt:14)
======
adn
Is the way to use out/in keywords a recommended practice? and Why?
Your code can be compiled without any warnings, this is because declaration-site variance only available in Kotlin.
This is in contrast with Java's use-site variance where wildcards in the type usages make the types covariant.
For example 2 Soruce interfaces use declaration-site variance in Kotlin:
interface Source<out T>
interface Source<in T>
Both of the two Source interfaces will be generated into the same source code in Java as below:
// v---`T extends Object` rather than `? extends T`
public interface Source<T>{ /**/ }
This is because wildcard ? is used as a type argument rather than a type parameter in Java.
The T in Source<T> is a type parameter and the ? extends String in Source<? extends String> is a type argument.
So if you use type projections to make the objects force to a List<out Any>, then the compiler will reports an UNCHECKED_CAST warning , for example:
fun demo(strs: List<String>) {
// v--- makes it explicitly by using out type proejction
val objects: List<out Any> = strs
if (objects is MutableList) {
// v--- an UNCHECKED_CAST warning reported
val obs: MutableList<Any> = objects as MutableList<Any>
obs.add(TextView())
}
}
In other words, you can't assign a List<out Any> to a MutableList<Any>. Otherwise, you will get a compilation error. for example:
fun demo(strs: List<String>) {
val objects: List<out Any> = strs
if (objects is MutableList) {
// v--- ? extends Object
//ERROR: can't assign MutableList<out Any> to Mutable<Any>
// v ^--- Object
val obs: MutableList<Any> = objects
obs.add(TextView())
}
}
IF you assign the objects to a MutableList<out Any> variable, you'll found that you can't adding anything, since you can't create Nothing in Kotlin at all. for example:
fun demo(strs: List<String>) {
val objects: List<out Any> = strs
if (objects is MutableList) {
// v--- down-casting to `MutableList<out Any>`
val obs: MutableList<out Any> = objects
// v---ERROR: can't be instantiated
obs.add(Nothing())
}
}
Q: Is the way to use out/in keywords a recommended practice?
Java has described how to use a wildcard and it also applies in Kotlin.
An "in" Variable, note "in" in here is ? extends T and it is same with Kotlin out variance:
An "in" variable serves up data to the code. Imagine a copy method with two arguments: copy(src, dest). The src argument provides the data to be copied, so it is the "in" parameter.
An "out" Variable, note "out" in here is ? super T and it is same with Kotlin in variance:
An "out" variable holds data for use elsewhere. In the copy example, copy(src, dest), the dest argument accepts data, so it is the "out" parameter.