【问题标题】:How to restrict type of a function argument如何限制函数参数的类型
【发布时间】:2018-05-09 17:57:41
【问题描述】:

假设我有以下功能:

def encode(obj)
  case obj
  when Int32
    "i#{obj}e"
  when String
    "#{obj.size}:#{obj}"
  when Symbol
    encode(obj.to_s)
  when Array
    obj.reduce "a" {|acc, i| acc + encode(i)} + "e"
  else
    raise ArgumentError.new "Cannot encode argument of class '#{obj.class}'"
  end
end

我想摆脱那个 else 分支来对参数的类型进行编译时检查。我可以这样写:

def encode(obj : Int32 | String | Symbol | Array)

在这种情况下没关系。但是如果有一个更大的类型列表呢?有没有更优雅的方法来做到这一点?我希望编译器检查这个函数是否只接受那些在 case 表达式中匹配的类型。

【问题讨论】:

    标签: switch-statement type-inference crystal-lang


    【解决方案1】:

    Overloading 救援:

    def encode(obj : Int32)
      "i#{obj}e"
    end
    
    def encode(obj : String)
      "#{obj.size}:#{obj}"
    end
    
    def encode(obj : Symbol)
      encode(obj.to_s)
    end
    
    def encode(obj : Array(String))
      obj.reduce "a" { |acc, i| acc + encode(i) } + "e"
    end
    

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 2023-01-20
      • 2023-02-22
      • 1970-01-01
      • 2020-10-11
      • 2016-10-28
      • 2020-08-26
      • 2017-08-31
      相关资源
      最近更新 更多