Types 创建抽象类型作为不同函数的包装器

Types 创建抽象类型作为不同函数的包装器,types,julia,Types,Julia,我正在尝试创建一个抽象类型,它是一个超类(称为内核)几个不同的函数,每个函数都是内核的子类,即 但是当我试图调用Model(ExpKernel)时,我得到了错误 ERROR: MethodError: Cannot `convert` an object of type Type{ExpKernel} to an object of type Kernel 这里的类型有什么我不知道的吗?这就是你要找的吗 julia> mutable struct Model ker

我正在尝试创建一个
抽象类型
,它是一个超类(称为
内核
)几个不同的函数,每个函数都是
内核
的子类,即

但是当我试图调用
Model(ExpKernel)
时,我得到了错误

ERROR: MethodError: Cannot `convert` an object of type Type{ExpKernel} to an object of type Kernel

这里的类型有什么我不知道的吗?

这就是你要找的吗

julia> mutable struct Model
           kernel::DataType

           Model(k::Type{<:Kernel}) =
               isconcretetype(k) ? new(k) : throw(ArgumentError("concrete type required"))
       end

julia> Model(GaussianKernel)
Model(GaussianKernel)

julia> Model(1)
ERROR: MethodError: no method matching Model(::Int64)
Closest candidates are:
  Model(::Type{var"#s1"} where var"#s1"<:Kernel) at REPL[4]:4
Stacktrace:
 [1] top-level scope at REPL[6]:1

julia> Model(Kernel)
ERROR: ArgumentError: concrete type required
Stacktrace:
 [1] Model(::Type{Kernel}) at .\REPL[4]:4
 [2] top-level scope at REPL[7]:1
julia>可变结构模型
内核::数据类型
模型(k::Type{Model(GaussianKernel)
模型(GaussianKernel)
朱莉娅>模型(1)
错误:MethodError:没有与模型匹配的方法(::Int64)
最接近的候选人是:
模型(::类型{var“#s1”}其中var“#s1”模型(内核)
错误:ArgumentError:需要具体类型
堆栈跟踪:
[1] 位于的模型(::Type{Kernel})。\REPL[4]:4
[2] REPL[7]处的顶级作用域:1

但请注意,这不是Julia中的典型设计模式-通常情况下,您会使用该模式来实现此类功能。

这就是您想要的吗

julia> mutable struct Model
           kernel::DataType

           Model(k::Type{<:Kernel}) =
               isconcretetype(k) ? new(k) : throw(ArgumentError("concrete type required"))
       end

julia> Model(GaussianKernel)
Model(GaussianKernel)

julia> Model(1)
ERROR: MethodError: no method matching Model(::Int64)
Closest candidates are:
  Model(::Type{var"#s1"} where var"#s1"<:Kernel) at REPL[4]:4
Stacktrace:
 [1] top-level scope at REPL[6]:1

julia> Model(Kernel)
ERROR: ArgumentError: concrete type required
Stacktrace:
 [1] Model(::Type{Kernel}) at .\REPL[4]:4
 [2] top-level scope at REPL[7]:1
julia>可变结构模型
内核::数据类型
模型(k::Type{Model(GaussianKernel)
模型(GaussianKernel)
朱莉娅>模型(1)
错误:MethodError:没有与模型匹配的方法(::Int64)
最接近的候选人是:
模型(::类型{var“#s1”}其中var“#s1”模型(内核)
错误:ArgumentError:需要具体类型
堆栈跟踪:
[1] 位于的模型(::Type{Kernel})。\REPL[4]:4
[2] REPL[7]处的顶级作用域:1
但请注意,这并不是Julia中的典型设计模式-通常您会使用该模式来实现此类功能

julia> mutable struct Model
           kernel::DataType

           Model(k::Type{<:Kernel}) =
               isconcretetype(k) ? new(k) : throw(ArgumentError("concrete type required"))
       end

julia> Model(GaussianKernel)
Model(GaussianKernel)

julia> Model(1)
ERROR: MethodError: no method matching Model(::Int64)
Closest candidates are:
  Model(::Type{var"#s1"} where var"#s1"<:Kernel) at REPL[4]:4
Stacktrace:
 [1] top-level scope at REPL[6]:1

julia> Model(Kernel)
ERROR: ArgumentError: concrete type required
Stacktrace:
 [1] Model(::Type{Kernel}) at .\REPL[4]:4
 [2] top-level scope at REPL[7]:1