代码之家  ›  专栏  ›  技术社区  ›  Bitwise

函数有多个子句,还声明默认值。

  •  1
  • Bitwise  · 技术社区  · 7 年前

    这是我的模块:

    defmodule Test do
      def try(10 = num, other_num \\ 10) do
        num + other_num
      end
      def try(_num, _other_num) do
        raise "This is incorrect"
      end
    end
    

    iex 我得到这个警告:

    warning: def try/2 has multiple clauses and also declares default values. In such cases, the default values should be defined in a header. Instead of:
    
        def foo(:first_clause, b \\ :default) do ... end
        def foo(:second_clause, b) do ... end
    
    one should write:
    
        def foo(a, b \\ :default)
        def foo(:first_clause, b) do ... end
        def foo(:second_clause, b) do ... end
    

    1 回复  |  直到 7 年前
        1
  •  12
  •   Dogbert    7 年前

    编译器希望您在指定默认值的地方编写一个函数头(即没有主体的函数)。

    def try(num, other_num \\ 10)
    def try(10 = num, other_num) do
      num + other_num
    end
    def try(_num, _other_num) do
      raise "This is incorrect"
    end
    

    这样做的原因是,用户无法为同一个函数指定不同的默认值,这是不明确的,因为Elixir编译器将具有默认值的函数编译为多个函数。

    def a(b, c \\ 10), do: b + c
    

    def a(b), do: a(b, 10)
    def a(b, c), do: b + c
    

    当函数指定不同的默认值时,没有直接的转换:

    def a(b, c \\ 10), do: b
    def a(b, c \\ 20), do: c