Nathan Basanese
Nathan Basanese

Reputation: 8876

Multiline comment in Elixir

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?

Upvotes: 34

Views: 22955

Answers (5)

TheWitheredStriker
TheWitheredStriker

Reputation: 41

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).

Upvotes: 2

Patrick Oscity
Patrick Oscity

Reputation: 54674

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

Upvotes: 36

owyongsk
owyongsk

Reputation: 2469

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
"""

Upvotes: 18

Kip
Kip

Reputation: 724

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
"""

Upvotes: 9

Dimagog
Dimagog

Reputation: 1925

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

Upvotes: 14

Related Questions