首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >高级T.type_parameter在Sorbet中的应用

高级T.type_parameter在Sorbet中的应用
EN

Stack Overflow用户
提问于 2019-08-11 23:23:33
回答 1查看 774关注 0票数 1

要编写通用方法,我只找到了sorbet.run上的这个例子sorbet.org/docs目前没有提到type_parameter。所以我有几个关于T.type_parameter的高级用法的问题。

  1. 限制父类型

如何指定只允许某一类型的子类型?(对于泛型类,使用type_member),例如只允许“可枚举”类型,因此我可以调用该对象上“枚举”中的所有内容。

  1. 工厂方法

我有一个方法来实例化给定类的对象。(例如,因为它使用的参数应该是私有的)。我该怎么写签名呢?

sorbet.run上的→视图

代码语言:javascript
复制
#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
EN

回答 1

Stack Overflow用户

发布于 2019-08-12 18:27:35

我想我找到了"1.限制父母类型“的答案。

尽管如此,我仍然没有找到"2.工厂方法“的解决方案。

特别是如何通过给定类的泛型类型指定返回值。

答: 1.限制父类型

五天前还在提交日志中。

在泛型中添加类型界(#1392)

看起来lower也可以省略。

sorbet.run上的→视图

代码语言:javascript
复制
# 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`
end

super.rb

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57454317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档