elixir - 19 . type specs

访问量: 238

参考:https://elixir-lang.org/getting-started/typespecs-and-behaviours.html

感觉就是javadoc...

# 用:: 来表示, 左侧是方法名称,右侧是应该返回的类型
@spec round(number) :: integer
def round(number), do: # implementation.

# 返回复杂类型
defmodule LousyCalculator do
  @spec add(number, number) :: {number, String.t}
  def add(x, y), do: {x + y, "You need a calculator to do that?!"}

  @spec multiply(number, number) :: {number, String.t}
  def multiply(x, y), do: {x * y, "Jeez, come on!"}
end


# 进一步,抽象代码,返回复杂类型(自定义类型)
defmodule LousyCalculator do
  @typedoc """
  Just a number followed by a string.
  """
  @type number_with_remark :: {number, String.t}

  @spec add(number, number) :: number_with_remark
  def add(x, y), do: {x + y, "You need a calculator to do that?"}

  @spec multiply(number, number) :: number_with_remark
  def multiply(x, y), do: {x * y, "It is like addition on steroids."}
end

订阅/RSS Feed

Subscribe

分类/category