Unit means the same in this context as void in Java. That means: Your getUserName method returns nothing. Therefore, the compiler complains rightfully that it cannot assign the value of getUserName (of type Unit) to a String variable.
This is because there is an error in the getUserName method. It's not doing what you want it to do. And I propose that this is because a misunderstanding on how to return and assign values. Let's take a look on your example method first:
def getUserName() { this.userName = userName }
First, note that in this context, this.userName and userName refer to the exact same instance variable. So, you are just overwriting the value of userName with the same value it contained before.
Here is what I assume you were thinking: "this.userName is the return value of getUserName, so I need to assign userName to it, so that the caller will get this value in return."
That's what I meant with the misunderstanding above. In Scala, you do not assign the return value of a function to a variable. Instead, you assign the function itself to a value. Look at this:
def getUserName() = userName
This means exactly what you want.
More than that, in Scala, you typically leave out the () after the method name if the method does not modify the state of the object. That would mean we write:
def getUserName = userName
However, a method that changes the internal state of the object should have the (). Example:
def resetUserName() {userName = ""}
Now, what about the braces?
Let me give you an example. Assume you want to write a message to the console every time the getter is called. For debugging, maybe. Your method would look like this:
def getUserName = { println("User name was requested.") userName }
You see a block of code here, after the equals sign. The return value of the function is the value of the last statement that is executed inside this block. Simple enough, we see it will be userName, which is what we want.
Like in Java, you can also use the return command in Scala. It is discouraged, but since it's supported by the syntax, I think it's good to mention it as well. Using the return statement, you can program your code just like you know it from Java:
def getUserName() { println("User name was requested.") return userName }
Note the absence of the equals sign. When you explicitly use the return statement, you don't need the equals sign.
I hope that helps. I suggest further reading on the syntax of the Scala programming language. Any good Google search result will do. The resources linked on the Scala home page are recommendable. For more depth, I recommend the book on Scala by Martin Odersky. It's pretty good.
UserandUserAccount