I understand what's going on here, but I don't know the right way to fix it. Consider the following code:
data class MyClass<T>(val a: T, val b: T)
val myVal = MyClass(1,2)
val myVal2 = MyClass(1,"b")
myVal1
is inferred to a type of MyClass<Int>
. This is what I want. But myVal2
is inferred to a MyClass<Any>
.
I understand that it's because Any
is a supertype of an Int
and a String
, but what I really want is a compiler error to get raised because 1
and "b"
are not matching types.
I would like to accomplish this with type inference, rather than explicitly declaring MyClass<Int>
.
I've looked at several other questions, but I they say that it's because the KProperty
object uses an out T
declaration. I don't have that issue here.
Motivation
I want this to build a class for defining comparison relationships, such as "equals", "greater than", etc. In my case I actually do want to use a KProperty
. For example,
data class equalTo(val prop: KProperty<*,T>, val compareTo: T)
.
Basically, the compiler should stop you if you try to define:
val myCompare = equalTo(MyClass::myStringProperty, 123)
Since it is nonsensical to ask if a String
property is equal to an Int
. There might be a better way to implement this concept. If so, please let me know.