I want to create a Scala class where one of its var is read-only from outside the class, but still a var. How can I do it?
If it was a val, there was no need to do anything. By default, the definition implies public access and read-only.
We call the class like a function, as User() , to create an instance of the class. It is also possible to explicitly use the new keyword, as new User() , although that is usually left out. User has a default constructor which takes no arguments because no constructor was defined.
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable.
Basic ClassClass variables are called, fields of the class and methods are called class methods. The class name works as a class constructor which can take a number of parameters. The above code defines two constructor arguments, xc and yc; they are both visible in the whole body of the class.
Type classes are a powerful and flexible concept that adds ad-hoc polymorphism to Scala. They are not a first-class citizen in the language, but other built-in mechanisms allow to writing them in Scala.
Define a public "getter" to a private var
.
scala> class Foo {
| private var _bar = 0
|
| def incBar() {
| _bar += 1
| }
|
| def bar = _bar
| }
defined class Foo
scala> val foo = new Foo
foo: Foo = Foo@1ff83a9
scala> foo.bar
res0: Int = 0
scala> foo.incBar()
scala> foo.bar
res2: Int = 1
scala> foo.bar = 4
<console>:7: error: value bar_= is not a member of Foo
foo.bar = 4
^
Define a trait with the "getter" method:
trait Foo { def bar: T }
Define a class which extends this trait, and which has your variable
private class FooImpl (var bar: T) extends Foo
Restrict the visibility of this class appropriately.
Having a dedicated interface allows you also to use multiple implementation classes at runtime, e.g. to cover special cases more efficiently, lazy loading etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With