kailua icon indicating copy to clipboard operation
kailua copied to clipboard

How to denote generic function that cast from parent class to child class?

Open JamesKim2998 opened this issue 7 years ago • 0 comments

I'm now trying to cast parent class(Component) to child class(WeaponComponent).

So I made function cast_to_weapon,

Component = class()
WeaponComponent = class()
--v function(parent: Component) --> WeaponComponent
function cast_to_weapon(parent)
    --# assume parent: WeaponComponent
    return parent
end

But as you can see, it's hard to reuse. Because, source type only can be Component, and destination type only can be WeaponComponent...

So I want to denote this like below,

--function(parent: Parent, childType: typeof(Child)) -> Child where Child extends Parent
function cast_to(parent, childType)
    return type
end

local parent = Component.new()
local child = cast_to(parent, WeaponComponent)

How can this be possible?

JamesKim2998 avatar May 06 '17 06:05 JamesKim2998