Strange behaviour when importing types in Scala 2.10 - scala

Today I cleared my .ivy cache and cleaned my project output targets. Since then I have been getting really strange behaviour when running tests with SBT or editing in the Scala IDE.
Given the following:
package com.abc.rest
import com.abc.utility.IdTLabel
I will get the following error:
object utility is not a member of package com.abc.rest.com.abc
Notice that com.abc is repeated twice, so it appears that the compiler uses the context of the current package when doing the import (maybe it's supposed to do this, but I never noticed it before).
Also, if I try to access classes in package com.abc from anywhere inside com.abc.rest (even using the full path) the compiler will complain that the type can not be found.
It appears that the errors only occur when I try to include files from parent packages. What I do find strange is that my code used to work. It only started happening after I cleaned up my project and my ivy cache, so maybe a later version of the compiler is more strict than the previous one.
I would love some ideas on what I can be doing wrong, or how I can go about troubleshooting this.
Update:
By first importing the parent classes and then defining the current package, the problem goes away:
import com.abc.utility.IdTLabel
import com.abs._
package com.abc.rest {
// Define classes belonging to com.abc.rest here
}
So this works, but I would still love to know why on earth the other way around worked, and then stopped working, and how on earth I can fix it. I had a good look, and could find no packages, objects or traits by the name of com anywhere inside the parent package.
Update relating to Worksheets:
Scala worksheets belonging to the same package share the same scope, which sounds obvious, but wasn't. Worksheets are not sand-boxed - they can see the project, and the project can see them. So all the 'test' object, traits, and classes you create inside the worksheet files, also becomes visible in the rest of the project.
I have so many worksheets that I did not even try to see where the problem came in. I simply moved them all to their own package, and like magic, the problem went away.
So, lesson learned for the day: If you create stuff inside worksheets, it's visible from outside the worksheet.
Anyway, this new found knowledge will come in handy, meaning anything 'interesting' can be build, monitored and tweaked inside the worksheet, while the rest of the project can actually use it. Quite cool actually.
It's still interesting to think how a sbt clean and cleaned up ivy cache managed to highlight the problem that was hidden before, but hey, that's another story....

(At the request of JacobusR, I'm making a proper answer out of my earlier comments).
This can happen if you have defined some class/trait/object inside package com.abc.rest.com. As soon as package com.abc.rest.com exists, and given that you are in package com.abc.rest, com would designate com.abc.rest.com as opposed to _root_.com. Fastest (but non-conclusive) way to check, without even scanning the source files, is to look for any .class files in the "com/abc/rest/com" sub-folder.
In particular you would get this behaviour if any of your files has duplicate package definitions (as in package com.abc.rest; package com.abc.rest; ...). If you have this duplicate package clause somewhere in the same file where you get the error, you wouldn't even see anything fishy with the .class files, as the failure at compiling the file would prevent the generation of .class files for any class definition inside the file.
The final bit of useful information is that as you found out the scala Worksheets are not sandboxed, and what you define in the worksheets affects your project's code (rather than only having the project's code affecting the worksheet). So a duplicate package clause in a worksheet could very well cause the error you got.

If package names conflict, there might be a custom error message for that. See if specifying the full path resolves the issue by starting from __root__. Ex. import __root__.com.foo.bar._

Related

Flutter imports: relative path or package?

In Flutter, for importing libraries within our own package's lib directory, should we use relative imports
import 'foo.dart'
or package import?
import 'package:my_app/lib/src/foo.dart'
Dart guidelines advocate to use relative imports :
PREFER relative paths when importing libraries within your own package’s lib directory.
whereas Provider package says to always use packages imports :
Always use package imports. Ex: import 'package:my_app/my_code.dart';
Is there a difference other than conciseness? Why would packages imports would reduce errors over relative imports?
From the same Dart guidelines, further down they give this reason for the relative imports:
There is no profound reason to prefer the former—it’s just shorter, and we want to be consistent.
Personally, I prefer the absolute method, despite it being more verbose, as it means when I'm importing from different dart files (in other folders), I don't have to work out where the file to be imported is, relative to the current file. Made-up example:
I have two dart files, at different folder levels, that need to import themes/style.dart:
One is widgets/animation/box_anim.dart, where the relative path import would be:
import '../../themes/style.dart';
The other is screens/home_screen.dart with the relative import:
import '../themes/style.dart';
This can get confusing, so I find it better to just use the absolute in both files, keeping it consistent:
import 'package:myapp/themes/style.dart';
And just stick that rule throughout. So, basically, whatever method you use - Consistency is key!
The Linter for Dart package, also has something to say about this, but is more about the Don'ts of mixing in the '/lib' folder:
DO avoid relative imports for files in lib/.
When mixing relative and absolute imports it's possible to create
confusion where the same member gets imported in two different ways.
An easy way to avoid that is to ensure you have no relative imports
that include lib/ in their paths.
TLDR; Choose the one you prefer, note that prefer_relative_imports is recommended in official Effective Dart guide
First of all, as mentioned in this answer, Provider do not recommands package imports anymore.
Dart linter provides a list of rules, including some predefined rulesets :
pedantic for rules enforced internally at Google
lints or even flutter_lints (previously effective_dart) for rules corresponding to the Effective Dart style guide
flutter for rules used in flutter analyze
Imports rules
There is actually more than two opposites rules concerning imports :
avoid_relative_lib_imports, enabled in pedantic and lints rulesets, basically recommend to avoid imports that have 'lib' in their paths.
The two following are the one you mention :
prefer_relative_imports, enabled in no predefined rulesets, but recommended in Effective Dart guide in opposition to :
always_use_package_imports, enabled in no predefined rulesets. Which means that it is up to you and to your preferences to enable it (be careful, it is incompatible with the previous rule)
Which one should I choose?
Choose the rule you want ! It will not cause any performance issue, and no rule would reduce errors over the other. Just pick one and make your imports consistent across all your project, thanks to Dart linter.
I personnaly prefer using prefer_relative_imports, as it is recommended by Dart team, with this VSCode extension which automatically fix and sort my imports.
Provider do not need packages imports anymore.
This was a workaround to an old Dart bug: Flutter: Retrieving top-level state from child returns null
TL;DR, by mixing relative and absolute imports, sometimes Dart created a duplicate of the class definition.
This led to the absurd line that is:
import 'package:myApp/test.dart' as absolute;
import './test.dart' as relative;
void main() {
print(relative.Test().runtimeType == absolute.Test().runtimeType); // false
}
Since provider relies on runtimeType to resolve objects, then this bug made provider unable to obtain an object in some situations.
My 5 cents on the topic are that absolute (package:my_app/etc/etc2...) imports cause much less trouble than relative ones (../../etc/etc2...) when you decide to reorganize/cleanup your project`s structure because whenever you move a file from one directory to another you change the "starting point" of every relative import that this file uses thus breaking all the relative imports inside the moved file...
I'd personally always prefer absolute to relative paths for this reason
This question already has good answers, but I wanted to mention an insanely annoying and hard-to-find problem I experienced with unit testing that was caused by a relative import.
The expect fail indicator for an exception-catching expect block
expect(
() => myFunction,
throwsA(isA<InvalidUserDataException>())
);
was showing the actual result as exactly the same as the expected result, and zero indication of why it's failing.
After massive trial-and-error, the issue was because the expected InvalidUserDataException (a custom-made class) was being imported to the test file in RELATIVE format vs PACKAGE format.
To find this, I had to compare side-by-side, line-by-line, call-by-call between this test file and another test file that uses the exact same exception expecters (It's lucky, we had this), and just by chance, I happened to scroll to the top of this file's imports and see the blue underline saying prefer relative imports to /lib directory.
No, they're not preferred; they're necessary, because the moment I changed that to a PACKAGE (absolute) import, everything suddenly started working.
What I learned from this is: Use absolute imports for test files (files outside the lib directory)
e.g. inside of src/test/main_test.dart
DON'T: use import '../lib/main.dart'
DO: use package:my_flutter_app/main.dart
Maybe other people knew this already, but I didn't, and I couldn't find anything online with searches about this issue, so I thought I would share my experience that might help others who got stuck around this.
Does anyone know why this happens?
Edit: For context, this happened while using Flutter 2.1.4 (stable) with Sound Null Safety
Do you use Integration Tests?
If the answer is yes, then in most cases you need to use package imports. When you attempt to run your integration tests on a physical device, any relative imports will not be able to find what they're looking for.
Example: https://github.com/fluttercommunity/get_it/issues/76
You can enforce package imports in your project by using these two linting rules:
always_use_package_imports
avoid_relative_lib_imports
I also prefer package imports because they stick even when rearranging your files and folders. Relative imports frequently break and it's a pain to have to remove them and reimport the offending dependency.
One very simple reason to not use package imports: rename your package without editing every dart file
Renaming can happen a few times while the product does not have a definitive name, and you or your product owner decides to change it.
It is much more painful to rename with package imports as your package name is in every import.
Of course you can change it with a find/replace query, but it's a useless edit on every dart file you can avoid with relative imports.
Plus, vscode allows to automatically update relative imports on file move/rename and I have never had any issue with this feature.

Newbie IDE (IntelliJ IDEA) issue: .class files not all usable

I'm working on a school project right now, and every time I have in the past, I always make a new Project in IntelliJ IDEA. However, this time she gave us some .class files that have methods in them that we can't see (she described what they do so we know how to use them) but need to use, so they have to be in the same folder, obviously.
SIDENOTE: I'm also new to using Macs, which is what I'm on at the moment.
Anyways, I put the .class files in my src folder that I found in the Project8 folder. I just made an array of the Book objects, which was one of the .class files I moved, and now I need to use a method from the other .class file, named BookInventory.class. I put that file in the src folder just like the other, but it won't let me use the only method in that class, which is LoadBooks.
Here is the LoadBooks signature:
public static void LoadBooks(Book[] b)
And here's the description of it that she gave to us:
"For each element in the array, accepts user input for the book, creates the Book object, and stores the object into the array."
So, when I made the array of Book objects, IDEA made an import statement up top all by itself, I didn't type it:
import java.awt.print.Book;
So why does IDEA recognize the Book.class file and allow me to use it in this .java file for my project, but it doesn't seem to notice the BookInventory.class file?
Any help appreciated, thanks ahead of time.
What is happening is when you first typed the line with LoadBooks(Book[] b), IntelliJ could not "see" your class files (you have subsequently loaded them in "class files" and added that as a project library, I presume).
IntelliJ however searched for and found a Book class in the internal java libraries, java.awt.print.Book. Note that this is a different class to the one your teacher gave you, which might have been e.g. edu.myschool.homework.Book.
Firstly, try to delete the line including the import statement, or manually change it to the correct package (your teacher can inform you what it is).
If the same import comes back automatically, you can go into Settings -> Editor -> General -> Auto Import and untick Add unambiguous imports on the fly - this will cause intellij to prompt you before adding imports.
Also, I would ask your teacher to give you the class files in a jar file, since that's the usual approach.
Good luck.

How to remove a form from a unit while keeping the unit in the project?

I use Delphi 7 and I encountered a very annoying thing. One of my projects has gone quite large and a form I used in one of the units became obsolete. I decided to get rid of it. It seems I can't. The IDE always asks for .dfm file, no matter what i tried (and I think i was very thorough).
Here's what I did:
First, I used the IDE's Remove from Project to remove the whole thing from the project. Then I commented out all sections that used anything in that unit and compiled, bulit and ran the project. It went without any errors or warnings. I saved all files and closed the Delphi IDE, started up a Notepad and removed the form's declaration from the unit, then deleted every associated file, except the .pas (with this, it became like any other regular unit).
Then I searched every file in the project's folder with Total Commander to see if any of them contained the name of the removed unit. None did.
I started Delphi and loaded the project.
With this I felt satisfied and added the unit's name to the uses list and pressed Compile.
IT STILL LOOKS FOR THE DAMNED DFM!!
If someone knows, please explain this to me. What did I miss?
If the compiler is looking for the .dfm file it will be because the compiler is including a unit that contains this:
{$R *.dfm}
That is what tells the compiler to link the .dfm file with the same name as the unit.
It seems likely that you still refer to the unit somewhere in your project. The compiler must be finding either a .pas file or a compiled .dcu file for your unit. Search for all files named <UnitName>.pas and <UnitName>.dcu. Remove these files. Then you will encounter compiler errors whenever you have code that attempts to use those units. Deal with those by removing the unit from the uses clause that names it. Then you should be done.

Does having multiple `package` declarations slow the compiler down?

I know that splitting a package declaration across multiple lines creates an implicit import. So this:
package com.me.project
package module
Is equal to:
package com.me.project.module
import com.me.project._
However, if an object in the project package changed, would it trigger sbt to recompile the current file, or would that depend on whether the changed object was actually invoked within the current scope? Basically, I'm wondering whether being more explicit, E.g:
package com.me.project.module
import com.me.project.UtilClass
import com.me.project.Rng
would help speed up compile times vs either of the first two approaches?
No, it wouldn't help to speed up anything. Actually, it could mean that your compilation times even increase because doing single imports mean that the compiler have to parse more lines of code. But because that would still only take nanoseconds it doesn't really count.
An import declaration is nothing more than an information to the compiler about where to look up declarations. A compiler doesn't need to do anything with that information unless you reference it from within your code. In this case the compiler has to compile that file too, in order to being able to find out if your code would typecheck or not.
In other words, if you actually use two declarations from a set of hundreds, they are the only ones that would trigger a recompilation of your source code when they change.
I don't say that this is the only possible behavior, because it could be implemented in any way, but implementing a compiler in a way that it triggers a recompilation of your code when the code that corresponds to an import declaration changes doesn't make a lot of sense, when you think about it, that is why it is very sure to say that it will not do it. Because, what would happen? Every source files probably contains a package declaration and some imports. If your code gets recompiled because one of a declaration in the range of a wildcard imports changes, then this needs to happen for all other files as well. And because you can be sure that in every application all the existing imports span more or less the entire classpath, the entire classpath needs to be recompiled just because one file changed, which is not the desired behavior.

Error with Groovy AST transformations when cleaning project in Eclipse

I'm trying to work through groovy's Implementing Local AST Transformations tutorial, but whenever I clean my project I get this error in each file that has the #WithLogging annotation in it:
Groovy:Could not find class for Transformation Processor AC.LoggingASTTransformation declared by AC.WithLogging
So you have a package named "AC" that contains both "WithLogging.groovy" and "LoggingASTTransformation.groovy" classes? Does it also contain any classes that implement the "WithLogging" interface?
If so, I'd suggest you move the class(es) that use your annotation to a location outside of the annotation defining package (the default will suffice, for diagnostic purposes) - Order of compilation matters with transformations. See this post on the groovy users mailing list for more on that.
Also try changing the annotation from #WithLogging to #AC.WithLogging.
As far as cleaning with Eclipse is concerned, I had a similar issue and found that I had to make a trivial modification after a clean to any file that contained my annotation. IE, add a space somewhere. Then save the file. This should rebuild everything properly.