0

I'm new to scala and would like to use class parameters to assign the value to a field of the same. In Java, we do similar thing within a constructor:

public class Test{

    private final int value;

    public Test(int value){
        this.value = value;
    }
}

Now, I tried to do a similar thing in Scala:

class Test(value: Int){
   val value = ..WHAT..value //Is there a way to assign a parameter value to a field with the same name?
}

object Test{
   def testMethod = //access value and do something with it.
}

Can we do something similar to what we can in do in Java?

1

2 Answers 2

1

Scala provides a shorter syntax for creating such a member - just add the keyword val before the argument name in the class parameter list. You can also add a modifier (e.g. private):

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Test(private val value: Int)

object Test {
  def testMethod(t: Test) = t.value
}

// Exiting paste mode, now interpreting.

defined class Test
defined module Test

scala> Test.testMethod(new Test(5))
res1: Int = 5
Sign up to request clarification or add additional context in comments.

3 Comments

AFAIK, it will make it a public member. As a Java programmer, we don't quite like making class members be public. Is it common in Scala?
@user3663882 Scala follows Uniform Access Principle. Check out.joelabrahamsson.com/learning-scala-part-nine-uniform-access
Huh, didn't think that we can declare such things. Thank you.
1

If you don't like exposing a private member, you could go for this:

class A {
  private var _quote = ""
  def quote = _quote
  def quote_=(newQuote: String) = _quote = newQuote
}

Which would you give you a getter and setter, both accessible by calling quote.

1 Comment

You can also make that private var, with its default value, an optional constructor parameter.

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.