1

Hi I am trying the String Concatenation operation in elixir. My code is as follows:

iex(1)> name="SHubham Agiwal"
        "SHubham Agiwal"
iex(2)> age =16
         16
iex(5)> "Hello" <> name <> "World" 
         "HelloSHubham AgiwalWorld"
iex(7)> "Hello" <> name <> "World" <>age
         ** (ArgumentError) argument error

As you can see, when I try to concat it with a single variable namely name, it gives me the output as HelloSHubham AgiwalWorld. But when I try to concat it with variables name and age I get Argument error. Can somebody let me know why I am getting this error?

6
  • 1
    Why do you expect string concatenation to work with integer? Commented Aug 31, 2017 at 3:36
  • I have experience in java. So was thinking if we could concat integers to string like we do in java. Apparently we can't in elixir Commented Aug 31, 2017 at 3:45
  • @mudasobwa can you post your answer so that I can accept it? Commented Aug 31, 2017 at 3:46
  • The answer provided by @bitwalker is absolutely correct, why would I post my own? We do call the instance of string “binary” in Elixir, that is kinda Erlang’s legacy. Commented Aug 31, 2017 at 3:51
  • @shubhamagiwal92 I confess I'm not long on Java knowledge but don't you have to cast an integer to string before you concatenate it--even in Java? Commented Aug 31, 2017 at 12:53

1 Answer 1

3

The problem is that age is not a binary. You can use interpolation instead for this, like "#{age}".

Sign up to request clarification or add additional context in comments.

2 Comments

...or to_string(age), or Integer.to_string(age).
@bitwalker You were right. The age is not binary. It is due to this that it is giving me a compile time error. using to_string solves the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.