crystal class 宏未编译
crystal class with macro not compiling
为了
class Y
def initialize(@a : String)
end
getter a
end
class X
macro test(name)
@{{name}} = y.{{name}}
end
@a : String
def initialize(y : Y)
test a
end
end
我得到了
instance variable '@a' of X was not initialized directly in all of the 'initialize' methods, rendering it nilable. Indirect initialization is not supported.
为什么?并将 @a 设置为 nil 确实解决了问题,但我认为这不是一个好的解决方法。
这是错误、设计限制还是我没有做正确的事?
是的,目前这是一个设计限制。引用来自 https://github.com/crystal-lang/crystal/issues/2731
的 Ary
Yes, this is expected behaviour. initialize must be simple enough for the compiler to analyze. A macro might be redefined in a subclass so resolving init is not trivial for a first pass.
This is a "won't fix" for me, or maybe we can mark it as an enhancement, but it won't happen soon (maybe never)
There's a hack I introduced to make initialization via macro possible: if {{@type}}
is mentioned then the compiler will lazily check the method on call. It's not documented, though. And it has several bugs. But for now it might be okay.
为了
class Y
def initialize(@a : String)
end
getter a
end
class X
macro test(name)
@{{name}} = y.{{name}}
end
@a : String
def initialize(y : Y)
test a
end
end
我得到了
instance variable '@a' of X was not initialized directly in all of the 'initialize' methods, rendering it nilable. Indirect initialization is not supported.
为什么?并将 @a 设置为 nil 确实解决了问题,但我认为这不是一个好的解决方法。
这是错误、设计限制还是我没有做正确的事?
是的,目前这是一个设计限制。引用来自 https://github.com/crystal-lang/crystal/issues/2731
的 AryYes, this is expected behaviour. initialize must be simple enough for the compiler to analyze. A macro might be redefined in a subclass so resolving init is not trivial for a first pass.
This is a "won't fix" for me, or maybe we can mark it as an enhancement, but it won't happen soon (maybe never)
There's a hack I introduced to make initialization via macro possible: if
{{@type}}
is mentioned then the compiler will lazily check the method on call. It's not documented, though. And it has several bugs. But for now it might be okay.