What you’d like to do is only possible with extension methods — and for good.
Actually, that’s what OOP is for — you should use inheritance, instead, as follows:
open class FooWrapper<T>(val value: T)
abstract class NumberWrapper<T : Number>(value: T) : FooWrapper<T>(
value = value
) {
abstract fun multiplyBy(otherValue: Int): Number
}
class IntWrapper(value: Int) : NumberWrapper<Int>(
value = value
) {
override fun multiplyBy(otherValue: Int): Int {
return value * otherValue;
}
}
Note that you can create custom operators like this:
abstract operator fun times(otherValue: Int): Number
instead of
abstract fun multiplyBy(otherValue: Int): Number
And since you seem to care a lot about Java interoperability, you might want to purse with your naming:
@JvmName(name = "multiplyBy")
abstract operator fun times(otherValue: Int): Number
However, I don’t know what your goal is, but making wrappers like this looks awful and pointless. You may want to use extension functions altogether, as opposed to wrapping values to add features to them. Alternatively, you may at least opt for composition so to avoid replicating the features of a type in its wrapper, as long as either the wrapped type is immutable or its state does not affect the state of its wrapper.
Example extension function for Fibonacci series:
fun Int.fibonacci(): Long =
fibonacci(n = this, a = 0, b = 1)
private tailrec fun fibonacci(n: Int, a: Long, b: Long): Long =
when (n) {
0 -> a
else -> fibonacci(n = n - 1, a = b, b = a + b)
}
/*
* Usage:
* 2.fibonacci() // to get the 2nd term of the Fibonacci series
*/
Composition:
class Wrapper<T>(val value: T)
fun Foo() {
Wrapper(10).value * 50;
}
Further suggestion:
In case you don’t need inheritance and want to wrap a specific type, you will likely benefit from value classes, especially when it comes to primitive types (which would need to get boxed before being passed to generic parameter, as the latter’s lower boundary can’t be a primitive type itself).
@JvmInline
value class IntWrapper(val value: Int)
If you could possibly be more specific about your purpose, we all would be able to help you better.