score:12
First, the error you're seeing (you didn't tell me what it is) isn't a runtime error. The thing
constructor isn't called when the thing
singleton is initialized -- it's called later when you call thing.apply
, so there's no circular reference at runtime.
Second, you do have a circular reference at compile time, but that doesn't cause a problem when you're compiling a scala file that you've saved on disk -- the compiler can even resolve circular references between different files. (I tested. I put your original code in a file and compiled it, and it worked fine.)
Your real problem comes from trying to run this code in the Scala REPL. Here's what the REPL does and why this is a problem in the REPL. You're entering object thing
and as soon as you finish, the REPL tries to compile it, because it's reached the end of a coherent chunk of code. (Semicolon inference was able to infer a semicolon at the end of the object, and that meant the compiler could get to work on that chunk of code.) But since you haven't defined class thing
it can't compile it. You have the same problem when you reverse the definitions of class thing
and object thing
.
The solution is to nest both class thing
and object thing
inside some outer object. This will defer compilation until that outer object is complete, at which point the compiler will see the definitions of class thing
and object thing
at the same time. You can run import thingwrapper._
right after that to make class thing
and object thing
available in global scope for the REPL. When you're ready to integrate your code into a file somewhere, just ditch the outer class thingwrapper
.
object thingwrapper{
//you only need a wrapper object in the REPL
object thing {
val someConst = 42
def apply(x: Int) = new thing(x)
}
class thing(x: Int) {
import thing.someConst
val field = x * someConst
override def toString = "val: " + field
}
}
score:0
Scala 2.12 or more could benefit for sip 23 which just (August 2016) pass to the next iteration (considered a “good idea”, but is a work-in-process)
Literal-based singleton types
Singleton types bridge the gap between the value level and the type level and hence allow the exploration in Scala of techniques which would typically only be available in languages with support for full-spectrum dependent types.
Scala’s type system can model constants (e.g.
42
,"foo"
,classOf[String]
).
These are inferred in cases likeobject O { final val x = 42 }
. They are used to denote and propagate compile time constants (See 6.24 Constant Expressions and discussion of “constant value definition” in 4.1 Value Declarations and Definitions).
However, there is no surface syntax to express such types. This makes people who need them, create macros that would provide workarounds to do just that (e.g. shapeless).
This can be changed in a relatively simple way, as the whole machinery to enable this is already present in the scala compiler.
type _42 = 42.type
type Unt = ().type
type _1 = 1 // .type is optional for literals
final val x = 1
type one = x.type // … but mandatory for identifiers
Source: stackoverflow.com
Related Query
- Scala singleton factories and class constants
- What's the difference between a companion object and a singleton class in Scala (Guice)
- Scala Singleton object for an extended class and pass parameters
- Difference between object and class in Scala
- What is the difference between a class and a type in Scala (and Java)?
- Scala class and case class == comparison
- Generating a class from string and instantiating it in Scala 2.10
- Mockito matchers, scala value class and NullPointerException
- Scala 2.10, its impact on JSON libraries and case class validation/creation
- Use Class Variables As Constants In Scala
- Scala class members and constructor parameters name clash
- Instantiate a Scala class from Java, and use the default parameters of the constructor
- Scala import statement at top and inside scala class
- Scala Error: Could not find or load main class in both Scala IDE and Eclipse
- Understanding Case class and Traits in Scala
- How to create a Scala class with private field with public getter, and primary constructor taking a parameter of the same name
- How can I syntax check a Scala script without executing the script and generating any class files?
- Scala getters and setters in Java class
- scala class constructors and abstract types
- Scala wont pattern match with java.lang.String and Case Class
- Scala getting field and type of field of a case class
- Scala enumerations with Singleton objects as enumeration elements and a possibility to iterate over them?
- Difference between conversion with implicit function and implicit class in Scala
- Problem with bounded type parameterised case class and default args in Scala
- Scala Puzzle: enforcing that two function arguments are of the same type AND both are a subtype of a given class
- Scala -- class declared fields and access modifiers
- Scala Play Framework - controller as class or singleton
- Implicit abstract class constructor parameter and inheritance in Scala
- Scala - how to create anonymous class and avoid hiding argument names
- How to call superclass constructor from child class in scala and how to do constructor chaining
More Query from same tag
- Why no dead code warning after return statement?
- Java cannot find symbol for imported scala class
- string interpolation does not work in function definition
- Filter in select using Slick
- Is there a way to sort values in a CSV file in Scala?
- wait for multiple scala-async
- Singletons only available once in Scala
- Spark - provide extra parameter to udf
- scala function literal and methods and underscore
- Possible to handle multi character delimiter in spark
- Table Cell renderer using Nimbus and Scala
- I'm trying to Inherite one object from another
- ScalaTest - testing equality between two floating point arrays with error margin
- How Akka cluster application health works?
- Iterate method list in Scala
- Pattern for parsing method parameters
- Scala's Empty Set: ... doesn't conform to expected type Set[Nothing]
- How to enforce creating new transaction in Lift Mapper?
- Type incorrectly inferred
- Update operations on a Scala Case Class
- Understanding implicit in Scala
- Find regular expression match in string after a given index in Scala
- Kinds not conforming with type lambda
- Scala visibility when accessed by Java classes
- Apache Spark reading UTF-16 CSV file
- IntelliJ repeatedly forgets that target src_managed is a source directory
- Migrating from Maven to SBT
- Scala on Android: java.lang.NoSuchMethodError: java.lang.String.isEmpty
- How to cast a string in Apache Flink Datastream in Scala?
- Check that Await.result doesn't return anything