Why must forward referenced values inside blocks in Scala be lazy? - scala

The scope of a name introduced by a declaration or definition is the
whole statement sequence containing the binding. However, there is a
restriction on forward references in blocks: In a statement sequence
s[1]...s[n] making up a block, if a simple name in s[i] refers to
an entity defined by s[j] where j >= i, then for all s[k]
between and including s[i] and s[j],
s[k] cannot be a variable definition.
If s[k] is a value definition, it must be lazy.
Edit: I am not sure Mikaël Mayer's answer actually explained everything. Consider:
object Test {
def main(args: Array[String]) {
println(x)
lazy val x: Int = 6
}
}
Here, the lazy value x definitely has to be read/evaluated before it is actually defined in the code! Which would contradict Mikaël's claim that lazy evaluation does away with the need to evaluate things before they are defined.

Normally you cannot have this:
val e: Int = 2
val a: Int = b+c
val b: Int = c
val c: Int = 1
val d: Int = 0
because value c is not yet defined at the time of the definition of a. Because a references c, all values between a and c should be lazy so that the dependency is avoided
val e: Int = 2
lazy val a: Int = b+c
lazy val b: Int = c
lazy val c: Int = 1
val d: Int = 0
This in fact translates a, b and c as objects whose value is initialized when it is read, which would be after the declaration, i.e. this would be equivalent to:
val e: Int = 2
var a: LazyEval[Int] = null
var b: LazyEval[Int] = null
var c: LazyEval[Int] = null
a = new LazyEval[Int] {
def evalInternal() = b.eval() + c.eval()
}
b = new LazyEval[Int] {
def evalInternal() = c.eval()
}
c = new LazyEval[Int] {
def evalInternal() = 1
}
val d = 0
where LazyEval would be something like the following (implemented by the compiler itself)
class LazyEval[T] {
var value: T = _
var computed: Boolean = false
def evalInternal(): T // Abstract method to be overriden
def eval(): T = {
if(computed) value else {
value = evalInternal()
computed = true
value
}
}
}
Edit
vals don't really exist in java. They are local variables or do not exist in computation. Therefore, the declaration of lazy val exists before anything is done. And remember that closures are implemented in Scala.
Your block would be rewritten as it:
object Test {
def main(args: Array[String]) {
// Declare all variables, val, vars.
var x: Lazy[Int] = null
// No more variables to declare. Lazy/or not variable definitions
x = new LazyEval[Int] {
def evalInternal() = 6
}
// Now the code starts
println(x)
}
}

You're trying to avoid references to entities which are provably uninitialized (or which are maybe uninitialized).
In a block, assignments occur in source order, but in a class template, members can be overridden and initialized early.
For instance,
{ val a = b ; val b = 1 } // if allowed, value of a is undefined
but in a template
class X { val a = b ; val b = 1 } // warning only
val x = new { override val b = 2 } with X
x.a // this is 2
class Y(override val b: Int) extends X // similarly
You also want to avoid this:
locally {
def a = c
val b = 2 // everything in-between must be lazy, too
def c = b + 1
}
Local objects are explicitly the same as lazy vals:
{ object p { val x = o.y } ; object o { val y = 1 } }
Other kinds of forward reference:
{ val x: X = 3 ; type X = Int }
The spec talks about forward references to "entities" -- a "name refers to an entity" -- which elsewhere means both terms and types, but obviously it really means only terms here.
It will let you harm yourself:
{ def a: Int = b ; def b: Int = a; a }
Maybe your mode of self-destruction must be well-defined. Then it's OK.

Related

How to understand this Scala function call

I am Scala beginner. Below Scala code runs well, but I cannot understand it. Log shows, line 19 finally run to line 12. How could it be?
object TestClassDef {
class Person {
private var _age = 0
def age:Int = _age
def age_=(newAge: Int) = {
_age = newAge
println("age changed to " + _age) // line 12
}
}
def main(args: Array[String]) {
var p = new Person()
// p.age_=(25)
p.age = 26 // line 19
}
}
If I get your question correctly, you're surprised that the method is called when you assign the value on line 19. This is because the _= (at the end of the age function with an Int parameter) means that it's an assignment operator (also see What are all the uses of an underscore in Scala?) so it does make sense that it's called when you simply type p.age = 26.
This is mutator
def age_=(newAge: Int) = {
_age = newAge
println("age changed to " + _age)
}
So the call
p.age = 26
is converted by compiler to
p.age_=(26)
which makes call to mutator.
Mutator naming conventions from http://docs.scala-lang.org/style/naming-conventions.html
For mutators, the name of the method should be the name of the property with “_=” appended. As long as a corresponding accessor with that particular property name is defined on the enclosing type, this convention will enable a call-site mutation syntax which mirrors assignment. Note that this is not just a convention but a requirement of the language.
Also to see what compiler is creating pass -Xprint:typer to the Scala compiler. For reference the above code with this parameter generates:
package <empty> {
object TestClassDef extends scala.AnyRef {
def <init>(): TestClassDef.type = {
TestClassDef.super.<init>();
()
};
class Person extends scala.AnyRef {
def <init>(): TestClassDef.Person = {
Person.super.<init>();
()
};
private[this] var _age: Int = 0;
<accessor> private def _age: Int = Person.this._age;
<accessor> private def _age_=(x$1: Int): Unit = Person.this._age = x$1;
def age: Int = Person.this._age;
def age_=(newAge: Int): Unit = {
Person.this._age_=(newAge);
scala.this.Predef.println("age changed to ".+(Person.this._age))
}
};
def main(args: Array[String]): Unit = {
var p: TestClassDef.Person = new TestClassDef.this.Person();
p.age_=(26)
}
}
}
Scala allows non-alphanumerics in identifiers (in two ways):
case 1:
(specialcharacters)*
scala> val ##*# = 1000000
scala> val #Alpha# = 1 // mixing alphanumerics not allowed
case 2:
letter(alphanumerics)* _ (specialcharacters)*
scala> val k12? = 1 // doesn't work, _ is mandatory
scala> val k12_? = 1
scala> val k12_?*&^% = 1
scala> val k12_?Alpha = 1 // doesn't work, can't mix alphanumeric
Special cases:
Some symbols/combination-of-symbols are reserved e.g. = # <%
scala> val # = 1 // doesn't work
scala> val ### = 1 // works fine
scala> val <% = 1 // doesn't work
scala> val <%> = 1 // works fine
Some symbol-combinations are special, _= can be used in method names but not in variable names.
scala> val k_= = 1 // doesn't work
scala> def k_= = 1 // works fine
method names ending in _= are setters.
if a class/object's setter method def x_= is defined along with a parameter-less method of same name def x, then x = e is interpreted as x_=(e)

Scala construct objects with or without arguments

In Scala, need a class that will construct a default object based on predefined computation (below the code may not be syntactically correct, but the idea is shown) if its no-params constructor is called. And I will be able to test its methods by creating an object with this(i, s) and parameters created outside. What is the best way to do that?
class myobj(i: Int, s: String) {
def this() = {
val j = 7 // in reality more computation with extra vals involved
val i = j
val str = "abcdefg"
val s = str.get(indexOf (i % 5))
this(i, s)
}
}
It might be better with a static factory:
class MyObj(i: Int, s: String)
object MyObj {
def apply() = {
val j = 7 // in reality more computation with extra vals involved
val i = j
val str = "abcdefg"
val s = ""
new MyObj(i, s)
}
}
Then you can just do:
val o = MyObj()

Scala values initialization

Why in this example, no error is thrown and b ends up holding default value?
scala> val b = a; val a = 5
b: Int = 0
a: Int = 5
When you do this in the REPL, you are effectively doing:
class Foobar { val b = a; val a = 5 }
b and a are assigned to in order, so at the time when you're assigning b, there is a field a, but it hasn't yet been assigned to, so it has the default value of 0. In Java, you can't do this because you can't reference a field before it is defined. I believe you can do this in Scala to allow lazy initialisation.
You can see this more clearly if you use the following code:
scala> class Foobar {
println("a=" + a)
val b = a
println("a=" + a)
val a = 5
println("a=" + a)
}
defined class Foobar
scala> new Foobar().b
a=0
a=0
a=5
res6: Int = 0
You can have the correct values assigned if you make a a method:
class Foobar { val b = a; def a = 5 }
defined class Foobar
scala> new Foobar().b
res2: Int = 5
or you can make b a lazy val:
scala> class Foobar { lazy val b = a; val a = 5 }
defined class Foobar
scala> new Foobar().b
res5: Int = 5

Why am I getting "is not a member" here? [duplicate]

This works:
class ButtonCountObserver {
private var cnt = 0 // private field
def count = cnt // reader method
def count_=(newCount: Int) = cnt = newCount // writer method
// ...
}
val b = new ButtonCountObserver
b.count = 0
But this doesn't
class ButtonCountObserver {
private var cnt = 0 // private field
def count_=(newCount: Int) = cnt = newCount // writer method
// ...
}
val b = new ButtonCountObserver
b.count = 0
I get: error: value count is not a member of ButtonCountObserver
Is it possible to create a setter (with the syntactic sugar) without a getter?
The spec requires that both a setter and getter are defined to be able to use the syntactic sugar for calling the setter:
The interpretation of an assignment to
a simple variable x = e depends on the
definition of x. If x denotes a
mutable variable, then the assignment
changes the current value of x to be
the result of evaluating the
expression e. The type of e is
expected to conform to the type of x.
If x is a parameterless function
defined in some template, and the same
template contains a setter function
x_= as member, then the assignment x =
e is interpreted as the invocation
x_=(e ) of that setter function.
Analogously, an assignment f .x = e to
a parameterless function x is
interpreted as the invocation f .x_=(e
). An assignment f (args) = e with a
function application to the left of
the ‘=’ operator is interpreted as f
.update(args, e ), i.e. the invocation
of an update function defined by f .
Furthermore, the getter must be visible in order to use the setter. I'm not sure if this is specified
Getter not visible #1
// error: method x cannot be accessed in x.Test
object x {
class Test {
private[this] var x0: Int = 0
private[Test] def x = x0
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
Getter not visible #2
//<console>:11: error: type mismatch; found : x.Test required: ?{val x: ?}
object x {
class Test {
private[this] var x0: Int = 0
private[this] def x = x0
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
Getter visible
object x {
class Test {
private[this] var x0: Int = 0
private[x] def x = x0
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
As retronym pointed out, there must be a getter present. As a workaround however (if you don't want to provide a getter), you can make the getter return Unit
object x {
class Test {
private[this] var x0: Int = 0
def x: Unit = ()
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
Don't think that that is considered good style (!), but it works.

Scala: can't write setter without getter?

This works:
class ButtonCountObserver {
private var cnt = 0 // private field
def count = cnt // reader method
def count_=(newCount: Int) = cnt = newCount // writer method
// ...
}
val b = new ButtonCountObserver
b.count = 0
But this doesn't
class ButtonCountObserver {
private var cnt = 0 // private field
def count_=(newCount: Int) = cnt = newCount // writer method
// ...
}
val b = new ButtonCountObserver
b.count = 0
I get: error: value count is not a member of ButtonCountObserver
Is it possible to create a setter (with the syntactic sugar) without a getter?
The spec requires that both a setter and getter are defined to be able to use the syntactic sugar for calling the setter:
The interpretation of an assignment to
a simple variable x = e depends on the
definition of x. If x denotes a
mutable variable, then the assignment
changes the current value of x to be
the result of evaluating the
expression e. The type of e is
expected to conform to the type of x.
If x is a parameterless function
defined in some template, and the same
template contains a setter function
x_= as member, then the assignment x =
e is interpreted as the invocation
x_=(e ) of that setter function.
Analogously, an assignment f .x = e to
a parameterless function x is
interpreted as the invocation f .x_=(e
). An assignment f (args) = e with a
function application to the left of
the ‘=’ operator is interpreted as f
.update(args, e ), i.e. the invocation
of an update function defined by f .
Furthermore, the getter must be visible in order to use the setter. I'm not sure if this is specified
Getter not visible #1
// error: method x cannot be accessed in x.Test
object x {
class Test {
private[this] var x0: Int = 0
private[Test] def x = x0
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
Getter not visible #2
//<console>:11: error: type mismatch; found : x.Test required: ?{val x: ?}
object x {
class Test {
private[this] var x0: Int = 0
private[this] def x = x0
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
Getter visible
object x {
class Test {
private[this] var x0: Int = 0
private[x] def x = x0
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
As retronym pointed out, there must be a getter present. As a workaround however (if you don't want to provide a getter), you can make the getter return Unit
object x {
class Test {
private[this] var x0: Int = 0
def x: Unit = ()
def x_=(a: Int) = x0 = a
}
val t = new Test
t.x = 1
}
Don't think that that is considered good style (!), but it works.