Julia UndefVarError:未定义子类型

Dam*_*ips 4 julia

不清楚为什么我ERROR: LoadError: UndefVarError: subtypes not defined在执行 .jl 文件时得到 ,但从 REPL 执行时却没有。

例如

abstract type Asset end

abstract type Property <: Asset end
abstract type Investment <: Asset end
abstract type Cash <: Asset end
println(subtypes(Asset))

> 3-element Array{Any,1}:
 Cash
 Investment
 Property
Run Code Online (Sandbox Code Playgroud)

...但将相同的代码放入test.jl

julia test.jl

> ERROR: LoadError: UndefVarError: subtypes not defined
Stacktrace:
 [1] top-level scope at /.../test.jl:6
 [2] include(::Module, ::String) at ./Base.jl:377
 [3] exec_options(::Base.JLOptions) at ./client.jl:288
 [4] _start() at ./client.jl:484
in expression starting at /.../test.jl:6
Run Code Online (Sandbox Code Playgroud)

Julia 版本 1.4.1,在 OSX Catalina (10.15.4) 上执行

Prz*_*fel 8

您需要using InteractiveUtils在调用之前添加subtypes。默认情况下,它在启动 Julia REPL 时已经加载。

因此,您的文件应如下所示:

shell> more t.jl

using InteractiveUtils
abstract type Asset end

abstract type Property <: Asset end
abstract type Investment <: Asset end
abstract type Cash <: Asset end
println(subtypes(Asset))


shell> julia t.jl
Any[Cash, Investment, Property]
Run Code Online (Sandbox Code Playgroud)