This page is no longer maintained — Please continue to the home page at

Constructor arguments and fields with the same name

1 reply
Chris Lambrou
Joined: 2009-01-11,
User offline. Last seen 42 years 45 weeks ago.
I'm fairly new to Scala, having come from a Java and C# background, and I have a question regarding name clashes between fields and constructor arguments. Consider the fairly common naming convention, shown in this simple java example:

public class MyClass {
  public String name;

  public MyClass(String name) { = name;

I'd like to be able to do the equivalent in a Scala class, a bit like the following, but am not sure how to do so correctly, or even if it's possible:

class MyClass(name: String) {
  val name: String = name   // Clearly nonsense.

I realise that there's no need to do this for case classes, since the constructor arguments are automatically exposed as public fields, but how can I do this for non-case classes? So far, I've been having to come up with two names for everything - one for the field and one for the constructor argument - which is a pain and can produce overly confusing code. I've been looking for an example of this in the Programming in Scala book, but this scenario seems to be inconveniently avoided, unfortunately.

Any help or advice would be much appreciated.

David Hall
Joined: 2008-12-28,
User offline. Last seen 42 years 45 weeks ago.
Re: Constructor arguments and fields with the same name

How's this:

scala> class Foo(val name: String);
defined class Foo

scala> new Foo("42").name
res0: String = 42

In case classes, "val" is implied.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland