Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Why do I need to "Moosh" var like this: intVar + ""; instead of just cast in as a string like this: (String) intVar?

For me, "mooshing" seams like a bad programming. And assuming that we already learn how to cast variables, why do we need to "moosh" them? And also, why its is even possible, why it is not an error?

1 Answer

There are other ways to do it, but not by casting. Casting will only work between types that are the same branch of the inheritance tree (either by extends or implements). Strings and primitive numbers aren't. When you use string concatenation with a piece that isn't a String Java will automatically call a method called toString() on it to turn in into one.

If fact, one of the other ways to do it is to just call toString() directly. With int variables you would write Integer.toString(intVar) in place of IntVar + "".

I see. I already tried to do this in the code (cast as string) and Android Studio fixed it to the toString() solution. So it was very helpful for me to understand why. Thank you!

The only thing... It is still strange. The compiler always throws an error when you try to save one type of var into another. Even if it's obvious and the Studio suggest only one solution to fix it. But at the same time it allows you to mix types during the concatenation. It's just strange..