要编写通用方法,我只找到了sorbet.run上的这个例子。sorbet.org/docs目前没有提到type_parameter。所以我有几个关于T.type_parameter的高级用法的问题。
如何指定只允许某一类型的子类型?(对于泛型类,使用type_member),例如只允许“可枚举”类型,因此我可以调用该对象上“枚举”中的所有内容。
我有一个方法来实例化给定类的对象。(例如,因为它使用的参数应该是私有的)。我该怎么写签名呢?
#typed: true
class Animal
def initialize(secret_of_nature); end
end
class Sidewinder < Animal
def rattle; end
end
class Nature
extend T::Sig
sig {params(animal_cls: T.class_of(Animal)).returns(Animal)}
def self.factory(animal_cls)
animal_cls.new(@secret_dna)
end
end
Nature::factory(Sidewinder).rattle
# => Method rattle does not exist on Animal发布于 2019-08-12 18:27:35
我想我找到了"1.限制父母类型“的答案。
尽管如此,我仍然没有找到"2.工厂方法“的解决方案。
特别是如何通过给定类的泛型类型指定返回值。
答: 1.限制父类型
五天前还在提交日志中。
看起来lower也可以省略。
# typed: true
class Animal; end
class Cat < Animal; end
class Serval < Cat; end
class A
extend T::Generic
T1 = type_member(lower: Serval, upper: Animal)
end
# should pass: Cat is within the bounds of T1
class B1 < A
extend T::Generic
T1 = type_member(fixed: Cat)
end
# should fail: String is not within the bounds
class B2 < A
extend T::Generic
T1 = type_member(fixed: String)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: parent lower bound `Serval` is not a subtype of lower bound `String`
# ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: upper bound `String` is not a subtype of parent upper bound `Animal`
end
# should pass: the bounds are a refinement of the ones on A
class C1 < A
extend T::Generic
T1 = type_member(lower: Serval, upper: Cat)
end
# should fail: the bounds are wider than on A
class C2 < A
extend T::Generic
T1 = type_member(lower: Serval, upper: Object)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: upper bound `Object` is not a subtype of parent upper bound `Animal`
end
# should fail: the implicit bounds of top and bottom are too wide for T1
class D1 < A
T1 = type_member
# ^^^^^^^^^^^ error: parent lower bound `Serval` is not a subtype of lower bound `T.noreturn`
# ^^^^^^^^^^^ error: upper bound `<any>` is not a subtype of parent upper bound `Animal`
endhttps://stackoverflow.com/questions/57454317
复制相似问题