Is it not a design flaw to have `Any` extend `Unit...
# announcements
a
Is it not a design flaw to have
Any
extend
Unit
? This would be nice for overriding functions…
p
Unit means no value, while Any expects value of reference type. If Any will extend Unit that would break function binary protocol. In other words, functions returning unit will not use place on call stack for return value, while functions returning Any will allocate on call stack for example 8 bytes on x64 for return value. So if you override function returning void by function returning Any you'll break layout on call stack.
k
Hmm not exactly,
Unit
doesn't really mean
void
, instead all functions actually return the single
Unit
object.
And no
Any
extending
Unit
doesn't really make sense, since
Unit
is just an ordinary class.
d
I get the idea, I think it's interesting. As a workaround, surely you can write your virtual functions to return Any for the time being.
p
If speaking low level now the compiler will not allocate extra space on call stack in case of function returning Unit. If Any will be subclass of Unit all overrideable functions returning void will be supposed to emit return value. At less it is performance degradation and binary compatabilty break. But what is the benefit?
If you supposed that you function will return anything in overriding implementations. Just daclare it like this in base class. And don't use it result when not needed
k
I understand where he's coming from, sometimes it would be nice to write stuff like this:
Copy code
interface Test {
    fun foo()
}

class MyTest: Test {
    fun bar() = 5
    override fun foo() = bar()
}
Or be able to pass a
() -> String
to something expecting
() -> Unit
. The JVM bytecode could still be generated the same way, so no performance impact.
p
Than it is another story. In that case compiler can substitute synthetic lamda returning Unit and calling target function
But it will not mean that Any is subclass of Unit. It will be just synthetic sugar for that cases
you will not be able to override return Unit function with returning Any
d
x is Unit
will always be true then so introducing such mechanism would be backward incompatible
r
@karelpeeters To be honest, I don't think it would be nice to write that, because it feels fundamentally untrue. I read that as "function
foo
is equivalent to function
bar
, but it's not.
Maybe it's just me, but I give different semantic meaning to
fun a() = b()
and
fun a() { b() }
, even when they are technically the same. (i.e. when both return
Unit
)
k
Yeah I agree, it's just an itch I have sometimes but I need to supress it better 😉
Mostly with lambdas it's frustrating that you can't just pass a
::foo
because it happens to return something.
r
Indeed