So I understand that in Scala, you can define something private within the scope of a specific package by adding the modifier private[packagename] where packagename is (obviously) the name of the package that you wish the reference to be private to.
So, for instance, let's say I have a package com.mycompany.usefulname with some class that has a field declared private[mycompany] - this will be accessible within all things in the com.mycompany.usefulname, as well as other things like perhaps com.mycompany.othername (or things simply in the com.mycompany, if for some reason I put something there).
What I'm wondering is this: if I do an awful design, where I have two different levels of my hierarchy using the same name, such as a package com.mycompany.mycompany, is there a way to specify which mycompany I would want something to be private within? Based on Package private modifier in Scala 2.8, it doesn't seem to be valid to specific private[com.mycompany], so how could I specify which one it would be?
Just to be clear, this is purely out of curiosity, and I'm not actually trying to make something with such an ambiguous name in the class hierarchy.
EDIT: To actually see what this does, I implemented the following hierarchy:
mycompany
mycompany
InnerObject.scala
usefulname
InnerObject2.scala
OuterObject.scala
InnerObject.scala is as follows:
object InnerObject {
private val privateVal = 7
private[mycompany] val packagePrivateVal = 8
val regularVal = 9
}
InnerObject2.scala is virtually identical:
object InnerObject2 {
private val privateVal = 7
private[mycompany] val packagePrivateVal = 8
val regularVal = 9
}
from OuterObject, I could reference:
InnerObject.regularVal
InnerObject2.packagePrivateVal
InnerObject2.regularVal
The regularVal isn't surprising, as this is public. The package private seems to be going up the hierarchy until it finds the first instance that matches the declaration of mycompany. So, can anyone tell me if/how to make it reference the outer one, rather than the inner one?
Here is the relevant excerpt (the example under the linked anchor) from the Scala language specification:
The following code illustrates the use of qualified private:
package outerpkg.innerpkg
class Outer {
class Inner {
private[Outer] def f()
private[innerpkg] def g()
private[outerpkg] def h()
}
}
Here, accesses to the method f can appear anywhere within OuterClass, but not outside it. Accesses to method g can appear anywhere within the package outerpkg.innerpkg, as would be the case for package-private methods in Java. Finally, accesses to method h can appear anywhere within package outerpkg, including packages contained in it.
There is no other mention of package-private access modifiers anywhere in the specs, at all. From this, I'd gather there is no way to deal with duplicate path nodes in the package name, and Scala will take the inner-most name that it finds, as you say.
In my opinion, that's a good thing, because duplicate names are redundant and confusing.
Related
What is the difference between
class Test {
private[this] val foo = 0
}
vs
class Test {
private val foo = 0
}
What all can go inside the []? Also, what should I search for when I want to look up the specs of this? I tried Googling various combinations of "scala access modifier arguments/parametrized scala access modifier" and nothing came up.
what should I search for when I want to look up the specs of this?
In The Scala Language Specification it is defined as "access modifier" and "access qualifier" (see BNF in §5.2).
What is the difference between
...
What all can go inside the []?
You can put class name, package name or this there. Here is a relevant quote from language specs that explains this (see §5.2 for more details):
The modifier can be qualified with an identifier C (e.g. private[C ]) that must
denote a class or package enclosing the definition. Members labeled with
such a modifier are accessible respectively only from code inside the package
C or only from code inside the class C and its companion module (§5.4).
An different form of qualification is private[this]. A member M marked
with this modifier is called object-protected; it can be accessed only from
within the object in which it is defined. That is, a selection p.M is only legal if the prefix is this or O.this, for some class O enclosing the reference. In
addition, the restrictions for unqualified private apply.
The first one is private for instance class, second is for class. If you use second version you have access from another instance of Test class (it's usefull for equals method or similiar).
I'm trying to wrap my head around the Scala language and figured the best way to learn is to put it into practice. When copy pasting code between a Java project (Spring) and my Scala project the IDE did a conversion I do not understand. Searching for it on the internet and in the docs gave me nothing to work with unfortunately.
The code:
#Bean private[context] def passwordEncoder: PasswordEncoder = {
return new BCryptPasswordEncoder
}
When compiling the above code the compiler complains:
`error: context is not an enclosing class`
Can anybody explain what the private[context] part means?
context is just a placeholder, where you can fill in the context in which you'd like the method to be private. This is optional though. If you don't specify the context, the member becomes "class-private", which afaik behaves like private does in Java.
Background: Scala offers more than one degree of access specification: the object-private specification, i.e. private[this], stipulates that the member in question can only be seen by members called on that same object, not from different objects, even if they are of the same type. Instead of this you can also use a package name or even root, which is an alias for the root namespace.
More information on this can be found in "Section 5.2 - Modifiers" of the Scala Language Reference:
The private modifier can be used with any definition or declaration in a template.
[...]
The modifier can be qualified with an identifier C (e.g. private[C]) that must denote a class or package enclosing the definition. Members labeled with such a modifier are accessible respectively only from code inside the package C or only from code inside the class C and its companion module (§5.4).
Starting with 2.10, -Xlint complains about classes defined inside of package objects. But why? Defining a class inside a package object should be exactly equivalent to defining the classes inside of a separate package with the same name, except a lot more convenient.
In my opinion, one of the serious design flaws in Scala is the inability to put anything other than a class-like entity (e.g. variable declarations, function definitions) at top level of a file. Instead, you're forced to put them into a separate ''package object'' (often in package.scala), separate from the rest of the code that they belong with and violating a basic programming rule which is that conceptually related code should be physically related as well. I don't see any reason why Scala can't conceptually allow anything at top level that it allows at lower levels, and anything non-class-like automatically gets placed into the package object, so that users never have to worry about it.
For example, in my case I have a util package, and under it I have a number of subpackages (util.io, util.text, util.time, util.os, util.math, util.distances, etc.) that group heterogeneous collections of functions, classes and sometimes variables that are semantically related. I currently store all the various functions, classes, etc. in a package object sitting in a file called io.scala or text.scala or whatever, in the util directory. This works great and it's very convenient because of the way functions and classes can be mixed, e.g. I can do something like:
package object math {
// Coordinates on a sphere
case class SphereCoord(lat: Double, long: Double) { ... }
// great-circle distance between two points
def spheredist(a: SphereCoord, b: SphereCoord) = ...
// Area of rectangle running along latitude/longitude lines
def rectArea(topleft: SphereCoord, botright: SphereCoord) = ...
// ...
// ...
// Exact-decimal functions
class DecimalInexactError extends Exception
// Format floating point value in decimal, error if can't do exactly
formatDecimalExactly(val num: Double) = ...
// ...
// ...
}
Without this, I would have to split the code up inconveniently according to fun vs. class rather than by semantics. The alternative, I suppose, is to put them in a normal object -- kind of defeating the purpose of having package objects in the first place.
But why? Defining a class inside a package object should be exactly equivalent to defining the classes inside of a separate package with the same name,
Precisely. The semantics are (currently) the same, so if you favor defining a class inside a package object, there should be a good reason. But the reality is that there is at least one good reason no to (keep reading).
except a lot more convenient
How is that more convenient?
If you are doing this:
package object mypkg {
class MyClass
}
You can just as well do the following:
package mypkg {
class MyClass
}
You'll even save a few characters in the process :)
Now, a good and concrete reason not to go overboard with package objects is that while packages are open, package objects are not.
A common scenario would be to have your code dispatched among several projects, with each project defining classes in the same package. No problem here.
On the other hand, a package object is (like any object) closed (as the spec puts it "There can be only one package object per package"). In other words,
you will only be able to define a package object in one of your projects.
If you attempt to define a package object for the same package in two distinct projects, bad things will happen, as you will effectively end up with two
distinct versions of the same JVM class (n our case you would end up with two "mypkg.class" files).
Depending on the cases you might end up with the compiler complaining that it cannot find something that you defined in the first version of your package object,
or get a "bad symbolic reference" error, or potentially even a runtime error. This is a general limitation of package objects, so you have to be aware of it.
In the case of defining classes inside a package object, the solution is simple: don't do it (given that you won't gain anything substantial compared to just defining the class as a top level).
For type aliase, vals and vars, we don't have such a luxuary, so in this case it is a matter of weighing whether the syntactic convenience (compared to defining them in an object) is worth it, and then take care not to define duplicate package objects.
I have not found a good answer to why this semantically equivalent operation would generate a lint warning. Methinks this is a lint bug. The only thing that I have found that must not be placed inside a package object (vs inside a plain package) is an object that implements main (or extends App).
Note that -Xlint also complains about implicit classes declared inside package objects, even though they cannot be declared at package scope. (See http://docs.scala-lang.org/overviews/core/implicit-classes.html for the rules on implicit classes.)
I figured out a trick that allows for all the benefits of package objects without the complaints about deprecation. In place of
package object foo {
...
}
you can do
protected class FooPackage {
...
}
package object foo extends FooPackage { }
Works the same but no complaint. Clear sign that the complaint itself is bogus.
A very strange thing indeed. I have the following project structure:
myproject/one/two
Inside package myproject I have a class:
abstract class A (two: Buffer[Int])
and then, inside package one I have:
object B extends A (Buffer[Int](1, 2, 3)) {
val с = two.map(_ + 1) // ERROR
}
However, the erros says:
object map is not a member of package
myproject/one/two
which is obviously erroneous because it should be perfectly clear that I don't refer to the packages here, but to the local variable... And two also is not shown in context-assist after this. in B, but is shown in A (Scala-IDE). Is this an intended behavior and I am doing something wrong or is it a bug?
UPDATE:
(simultaneously suggested by Nicolas :D ) Been able to resolve the name collision by specifying two as val (making it public). I did not notice at first, but it was private and unavailable in the successor class. Nevertheless I am still wondering, why and how did Scala pick up a package instead of saying that the variable does not exist or is not accessible?
It's not as clear as you might think. Without a modifier, two is private to abstract class A class A. Thus your declaration of a is equivalent to abstract class A (private[this] A). It means that field two can't be seen from object B. A direct consequence is that the compiler look into the only defiition of two visible from B: the package two.
Ok, I'll explain why I ask this question. I begin to read Lift 2.2 source code these days.
It's good if you happened to read lift source code before.
In Lift, I found that, define inner class and inner trait are very heavily used.
object Menu has 2 inner traits and 4 inner classes. object Loc has 18 inner classes, 5 inner traits, 7 inner objects.
There're tons of codes write like this. I wanna to know why the author write like this.
Is it because it's the author's
personal taste or a powerful use of
language feature?
Is there any trade-off for this kind
of usage?
Before 2.8, you had to choose between packages and objects. The problem with packages is that they cannot contain methods or vals on their own. So you have to put all those inside another object, which can get awkward. Observe:
object Encrypt {
private val magicConstant = 0x12345678
def encryptInt(i: Int) = i ^ magicConstant
class EncryptIterator(ii: Iterator[Int]) extends Iterator[Int] {
def hasNext = ii.hasNext
def next = encryptInt(ii.next)
}
}
Now you can import Encrypt._ and gain access to the method encryptInt as well as the class EncryptIterator. Handy!
In contrast,
package encrypt {
object Encrypt {
private[encrypt] val magicConstant = 0x12345678
def encryptInt(i: Int) = i ^ magicConstant
}
class EncryptIterator(ii: Iterator[Int]) extends Iterator[Int] {
def hasNext = ii.hasNext
def next = Encrypt.encryptInt(ii.next)
}
}
It's not a huge difference, but it makes the user import both encrypt._ and encrypt.Encrypt._ or have to keep writing Encrypt.encryptInt over and over. Why not just use an object instead, as in the first pattern? (There's really no performance penalty, since nested classes aren't actually Java inner classes under the hood; they're just regular classes as far as the JVM knows, but with fancy names that tell you that they're nested.)
In 2.8, you can have your cake and eat it too: call the thing a package object, and the compiler will rewrite the code for you so it actually looks like the second example under the hood (except the object Encrypt is actually called package internally), but behaves like the first example in terms of namespace--the vals and defs are right there without needing an extra import.
Thus, projects that were started pre-2.8 often use objects to enclose lots of stuff as if they were a package. Post-2.8, one of the main motivations has been removed. (But just to be clear, using an object still doesn't hurt; it's more that it's conceptually misleading than that it has a negative impact on performance or whatnot.)
(P.S. Please, please don't try to actually encrypt anything that way except as an example or a joke!)
Putting classes, traits and objects in an object is sometimes required when you want to use abstract type variables, see e.g. http://programming-scala.labs.oreilly.com/ch12.html#_parameterized_types_vs_abstract_types
It can be both. Among other things, an instance of an inner class/trait has access to the variables of its parent. Inner classes have to be created with a parent instance, which is an instance of the outer type.
In other cases, it's probably just a way of grouping closely related things, as in your object example. Note that the trait LocParam is sealed, which means that all subclasses have to be in the same compile unit/file.
sblundy has a decent answer. One thing to add is that only with Scala 2.8 do you have package objects which let you group similar things in a package namespace without making a completely separate object. For that reason I will be updating my Lift Modules proposal to use a package object instead of a simple object.