Multiline comment in Elixir

21.4k views Asked by At

Most languages allow block comments, and multiline commands.

For example, a multiline comment in HTML looks like the following:

<!-- 
Warning, brave programmer:
Here be dragons.
-->

In Elixir, the closest thing I have found comes from EEx (docs).

EEx smartengine <% #comments %> seem to be discarded from source, even if they are multiline. However, this is just a workaround.

Does Elixir have a multiline comment feature, or a way to instruct the compiler to discard text from the compiled .beam file?

5

There are 5 answers

10
Patrick Oscity On BEST ANSWER

Elixir does not have multiline comments.

However, one very common use case for multiline comments is documenting modules and functions, for which you can use the module attributes @doc and @moduledoc together with heredocs.

defmodule MyModule do
  @moduledoc """
  This module is great at X
  """

  @doc """
  Frobnicates the given string.
  """
  def frobnicate(s) do
  end
end
6
owyongsk On

I try to just use """ to quickly comment code a la Python, without turning it into a documentation

"""
def some_function() do
  some_code    
end
"""
5
Dimagog On

Macros could help here to some degree:

defmodule Comment do
  defmacro comment(_text) do
  end
end

defmodule TestComment do
  import Comment

  comment """
  Module
  Comment
  """

  def func do
    comment """
    Function
    Comment
    """
  end
end
0
TheWitheredStriker On

I know I'm late and that this question has already been answered, but I found a way that works, using a sigil that prevents string interpolation. I figured I could share it for others who stumble upon this post.

~S"""
Hi! 
I'm a
multiline comment!
"""

This works in modules and functions too, including if it is the last thing in the block. Unlike regular string literals (i.e. without the ~s sigil prepended to it), this does not throw an error or warning.

Keep in mind that this is not an official language feature. Out of the box, Elixir only supports single-line comments (# Comment) and the module documentation syntax (@moduledoc / @doc).

4
Kip On

You can simply use module attributes for multiline comments, no macro required. I typically use the following for documenting/commenting private functions:

@docp """
This is my
multi line
comment
"""