score:11
Whether this is indeed a design flaw is rather debatable. One would consider that complicating the syntax to allow this particular use case is not worthwhile.
Also, Scala is after all a predominantly functional language, so the presence of vars in your program should not be that frequent, again raising the question if this particular use case needs to be handled in a special way.
However, it seems that a simple solution to your problem would be to use an apply
method in the companion object:
class Foo private(private var _x: Int) {
def x = _x
}
object Foo {
def apply(x: Int): Foo = new Foo(x)
}
Usage:
val f = Foo(x = 3)
println(f.x)
LATER EDIT:
Here is a solution similar to what you originally requested, but that changes the naming a bit:
class Foo(initialX: Int) {
private var _x = initialX
def x = _x
}
Usage:
val f = new Foo(initialX = 3)
score:0
The concept you are trying to express, which is an object whose state is mutable from within the object and yet immutable from the perspective of other objects ... that would probably be expressed as an Akka actor within the context of an actor system. Outside the context of an actor system, it would seem to be a Java conception of what it means to be an object, transplanted to Scala.
import akka.actor.Actor
class Foo(var x: Int) extends Actor {
import Foo._
def receive = {
case WhatIsX => sender ! x
}
}
object Foo {
object WhatIsX
}
score:0
Not sure about earlier versions, but In Scala 3 it can easily be implemented like follows:
// class with no argument constructor
class Foo {
// prive field
private var _x: Int = 0
// public getter
def x: Int = _x
// public setter
def x_=(newValue: Int): Unit =
_x = newValue
//auxiliary constructor
def this(value: Int) =
this()
_x = value
}
Note
- Any definition within the primary constructor makes the definition public, unless you prepend it with
private
modifier - Append
_=
after a method name withUnit
return type to make it a setter - Prepending a constructor parameter neither with
val
nor withvar
, makes it private
Then it follows:
val noArgFoo = Foo() // no argument case
println(noArgFoo.x) // the public getter prints 0
val withArgFoo = Foo(5) // with argument case
println(withArgFoo.x) // the public getter prints 5
noArgFoo.x = 100 // use the public setter to update x value
println(noArgFoo.x) // the public getter prints 100
withArgFoo.x = 1000 // use the public setter to update x value
println(withArgFoo.x) // the public getter prints 1000
This solution is exactly what you asked; in a principled way and without any ad hoc workaround e.g. using companion objects and the apply
method.
Source: stackoverflow.com
Related Query
- How to create a Scala class with private field with public getter, and primary constructor taking a parameter of the same name
- Scala - how to create anonymous class and avoid hiding argument names
- How to create new instance of Scala class with context bound via Java reflection using only zero argument constructor?
- How do I create horizontal or vertical struts and glue for use with scala BoxPanel?
- how to extend (or proxy) a scala class with private constructor
- how to create scala case class with struct types?
- How to create an instance of a model with the ebean framework and scala in Play 2.2
- How to create a scala case class instance with a Map instance
- How do I use scala and scalatest to see if a list contains an object with a field matching a specific value
- How to get Scala case class fields and values as (String, String) with Shapeless or Macro
- How can I call Scala function with class name and function name as strings
- How do I create a class hierarchy of typed factory method constructors and access them from Scala using abstract types?
- Scala - How to create a class with a constructor that receives an object as parameter
- Class with covariant type parameter and private constructor in Scala
- Scala class with a private constructor and implicit parameter
- How to create a Scala executable jar file that is built with Maven, and has log4j included, using IntelliJ IDEA IDE
- How Scala allows overriding with type parameters and not with type class
- Scala - How to create a combine ArrayList of functions with and without parameters
- How to define case class with a list of tuples and access the tuples in scala
- How do I create a periodic Poller with Play 2.0 and Scala
- scala how to use pattern matching with inheriance and templated class
- How to parse a csv with matching case class and store the output to treemap[Int, List[List[InputConfig]] object in scala
- How to list annotations (custom java ones and others) on field members of Scala case class
- Is it possible to convert between two case class with different name and slightly different field in scala
- How to create Scala class with my IDEA?
- Scala Specs2 (version 3.x) - How create and work with Notifier?
- An umbrella Scala project. How to create multimodules project with multiple versions of scala, and libs?
- How to create new empty column in Spark by Scala with just column name and data type
- how to create scala class similar to java bean but with simple logic to modify the input
- How to clone a case class instance and change just one field in Scala?
More Query from same tag
- For comprehension and number of function creation
- Exception Passing Through scala.concurrent.Future?
- Scala - Instantiate classes dynamically from a String
- Scala equivalent for ActiveSupport's Object.try in Ruby
- Debugging a Scala project (IntelliJ Idea 12 and sbt)
- How do i handle Nulls in pattern matching in spark scala
- Possible to handle multi character delimiter in spark
- How to solve "Implementation restriction: trait ... accesses protected method ... inside a concrete trait method."
- "Insecure HTTP request is unsupported" Error in Scala
- How to group by gender and join by positions per group?
- Spark Dataframe/RDD cannot create new column by counting the contents of another column
- How to run a java program upon compilation of class
- Conditional routes/routing and Play 2.0
- How can I get the elements of list using ListBuffer
- Flattening a Set of pairs of sets to one pair of sets
- Spark DataFrame - distinguish between a record having a missing column vs a bad value
- What type parameters should I use to make List.map work with delimited continuations?
- I use the playframework2, in view template, how to use another template which I defined by myself?
- Why is Dataproc using this weird shaded version of the JSON package and how do I work with it?
- [Slick 2.0]: How to translate subqueries from sql to Slick
- Dropwizard/Jersey/HK2 Dependency Injection in Scala
- Why does the Scala compiler prefer to infer an argument of value null as Array[Char] instead of Object?
- Enriching SparkContext without incurring in serialization issues
- Type resolution with higher kinded types and implicits
- Spark: How to save the output (saveAsTextFile) to files with equal size?
- scala Futures: possible to find out if an 'onFailure' callback has been installed (so we can implement default error handling)?
- Spray rejections is not converted to status code?
- string interpolation does not work in function definition
- Akka HTTP custom headers: error in documentation or unfamiliar syntax?
- Scala pattern matching on generic Map