When exactly do you need to import in java? - class

The following unexpectedly compiled and ran without a problem:
import info.gridworld.actor.Actor;
import java.util.ArrayList;
public class ChameleonKid extends ChameleonCritter
{
public ArrayList<Actor> getActors()
{
ArrayList<Actor> actors = getGrid().getNeighbors(getLocation());
ArrayList<Actor> frontBack = new ArrayList<Actor>();
for(Actor i : actors)
if(getLocation().getDirectionToward(i.getLocation())==getDirection())
frontBack.add(i);
return frontBack;
}
}
The method getLocation() in the Actor class returns an instance of Location. And then I call the getDirectionToward() method of the Location class. getLocation().getDirectionToward(i.getLocation()). How does this work? I never imported the Location class. How am I able to work with it and call its methods? If that is how it works, when would I need to import a class? Only if I am instantiating it?
I am using Java 7.

Say you have two methods, one returning foo.Location and the other returning bar.Location (two completely different classes happening to have the same name, but in different packages - completely valid):
foo.Location getFooLocation();
bar.Location getBarLocation();
When you can both of these methods in the same class and chain some methods, you don't need an import:
if(getFooLocation().onlyInFoo()) {
//...
}
if(getBarLocation().onlyInBar()) {
//...
}
It works because the compiler is completely sure which version (from which package) of Location are you using and it knows where onlyInFoo() and onlyInBar are available.
But suppose you need a local variable:
Location location;
// much later
location = getFooLocation();
Now the compiler doesn't really know Location do you mean, so you must help him either by proceeding class name with package:
foo.Location location;
or by importing that class:
import foo.Location;
You should now ask: what if I want to have local variable of both foo.Location and bar.Location? Well, you can't import them both, obviously:
//WRONG
import foo.Location;
import bar.Location;
What you can do is again: either don't import at all and use fully qualified names:
foo.Location location1;
bar.Location location;
...or import just one location:
import foo.Location;
//...
Location location1; //foo.Location
bar.Location location2;

The reason why you don't need to import that class is because of the fact that you are not explicitly using that class. Actor is the one actually using the Location class locally. You are never holding a reference to the Location class and so, you are able to keep using it dynamically. However, if you wanted to hold a reference (eg Location l = getLocation();), you would have to import Location since the compiler has to link l with Location, but has no idea where to find it.

Related

How do you import files in flutter?

I'm facing an issue where I'm trying to split the code up into different files (to make it neater). So far the import is working except for one file.
Currently, my flutter project is setup in this manner
However, one of my files is not importing correctly.
This is my chorusSearch.dart file:
I've tried importing a class from chorusPage.dart. But the import is not resolving.
What is wrong here? This is my chorusPage.dart file.
You cannot call a method or a function of a class that should be instantiated.
You are trying to access a method inside a private class (with the _ char before) of a class that should be initialized before.
If you want to create functions that don't require a view, a page and nothing visual you should make public and static classes and create something like an utility.dart class that contains them.
Then you can call Utility.yourfunction() from where you want
A little example
file utility.dart in lib/utils/
void your_method() {
//do something
}
then in place you can import the file utility.dart and you can also assign to it a name with "as" like this -> import 'package:appname/utils/utility.dart' as Utility;
then you can use Utility.your_method()

Undeclared type: createM3FromEclipseProject (Rascal)

In the following module, I tried to add myModel for debugging purpose to see the AST.
module FlowGraphsAndClassDiagrams
import analysis::flow::ObjectFlow;
import lang::java::flow::JavaToObjectFlow;
// Added to check the M3 model
import lang::java::jdt::m3::AST;
import List;
import Relation;
import lang::java::m3::Core;
import IO;
import vis::Figure;
import vis::Render;
import analysis::m3::TypeSymbol;
alias OFG = rel[loc from, loc to];
//To view the M3 model from the whole eclipse project
alias myModel = createM3FromEclipseProject(loc project);
....
When I import the above module in the rascal console, I get the following error:
Reloading module FlowGraphsAndClassDiagrams
|console:///|:Could not load FlowGraphsAndClassDiagrams
|console:///|:could not reimport FlowGraphsAndClassDiagrams
|project://my_project/src/FlowGraphsAndClassDiagrams.rsc|(428,26,<18,16>,<18,42>): Undeclared type: createM3FromEclipseProject
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredType/UndeclaredType.html|
I don't understand what the mistake is.
I think the problem lies with
alias myModel = createM3FromEclipseProject(loc project);
What are you trying to achieve with this alias? I think you don't want to use an alias, instead you want to do this:
m = createM3FromEclipseProject(|project://eLib|);
println(m);
http://tutor.rascal-mpl.org/Rascal/Rascal.html#/Rascal/Declarations/Alias/Alias.html
You can use alias to create a new name for types, while createM3FromEclipseProject(loc project) seems to be a declaration of a function. If you want to call a function, which you seem to be doing, you need to provide a variable/value as parameter: createM3FromEclipseProject(|project://eLib|) if you want to "create an M3" from eclipse project "eLib".
Both answers are right, you can't use aliases for global variables. If you want to make an global variable (which in most cases we advice against), you have to give the type of that variable. We only allow type inference for local variables.
So in your specific case it should be:
M3 myModel = createM3FromEclipseProject(|project://eLib|);
In most cases you want to do this in your main method instead of at module import time.

How do I import a Swift file from another Swift file?

I simply want to include my Swift class from another file, like its test
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel { }
PrimeNumberModelTests.swift
import XCTest
import PrimeNumberModel // gives me "No such module 'PrimeNumberModel'"
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel() // "Use of unresolved identifier 'PrimeNumberModel'"
}
Both swift files are in the same directory.
I had the same problem, also in my XCTestCase files, but not in the regular project files.
To get rid of the:
Use of unresolved identifier 'PrimeNumberModel'
I needed to import the base module in the test file. In my case, my target is called 'myproject' and I added import myproject and the class was recognised.
UPDATE Swift 2.x, 3.x, 4.x and 5.x
Now you don't need to add the public to the methods to test then.
On newer versions of Swift it's only necessary to add the #testable keyword.
PrimeNumberModelTests.swift
import XCTest
#testable import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
And your internal methods can keep Internal
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel {
init() {
}
}
Note that private (and fileprivate) symbols are not available even with using #testable.
Swift 1.x
There are two relevant concepts from Swift here (As Xcode 6 beta 6).
You don't need to import Swift classes, but you need to import external modules (targets)
The Default Access Control level in Swift is Internal access
Considering that tests are on another target on PrimeNumberModelTests.swift you need to import the target that contains the class that you want to test, if your target is called MyProject will need to add import MyProject to the PrimeNumberModelTests:
PrimeNumberModelTests.swift
import XCTest
import MyProject
class PrimeNumberModelTests: XCTestCase {
let testObject = PrimeNumberModel()
}
But this is not enough to test your class PrimeNumberModel, since the default Access Control level is Internal Access, your class won't be visible to the test bundle, so you need to make it Public Access and all the methods that you want to test:
PrimeNumberModel.swift
import Foundation
public class PrimeNumberModel {
public init() {
}
}
In the Documentation it says there are no import statements in Swift.
Simply use:
let primNumber = PrimeNumberModel()
Check target-membership of PrimeNumberModel.swift in your testing target.
In Objective-C, if you wanted to use a class in another file you had to import it:
#import "SomeClass.h"
However, in Swift, you don't have to import at all. Simply use it as if it was already imported.
Example
// This is a file named SomeClass.swift
class SomeClass : NSObject {
}
// This is a different file, named OtherClass.swift
class OtherClass : NSObject {
let object = SomeClass()
}
As you can see, no import was needed. Hope this helps.
According To Apple you don't need an import for swift files in the Same Target. I finally got it working by adding my swift file to both my regular target and test target. Then I used the bridging header for test to make sure my ObjC files that I referenced in my regular bridging header were available. Ran like a charm now.
import XCTest
//Optionally you can import the whole Objc Module by doing #import ModuleName
class HHASettings_Tests: XCTestCase {
override func setUp() {
let x : SettingsTableViewController = SettingsTableViewController()
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
SO make sure PrimeNumberModel has a target of your test Target. Or High6 solution of importing your whole module will work
I was able to solve this problem by cleaning my build.
Top menu -> Product -> Clean
Or keyboard shortcut: Shift+Cmd+K
As of Swift 2.0, best practice is:
Add the line #testable import MyApp to the top of your tests file, where "MyApp" is the Product Module Name of your app target (viewable in your app target's build settings). That's it.
(Note that the product module name will be the same as your app target's name unless your app target's name contains spaces, which will be replaced with underscores. For example, if my app target was called "Fun Game" I'd write #testable import Fun_Game at the top of my tests.)
Check your PrimeNumberModelTests Target Settings.
If you can't see PrimeNumberModel.swift file in Build Phases/Compile Sources, add it.
You need to add a routine for the compiler to reference as an entry point, so add a main.swift file, which in this case simply creates an instance of your test file:
main.swift
PrimeNumberModelTests()
Then compile on the command line (I am using El Capitan and Swift 2.2):
xcrun -sdk macosx swiftc -emit-executable -o PrimeNumberMain PrimeNumberModel.swift PrimeNumberModelTests.swift main.swift
In this case, you will get a warning: result of initializer is unused, but the program compiles and is executable:
./PrimeNumberMain
CAVEAT: I removed the import XCTest and XCTestCase type for simplicity.
So, you need to
Import external modules you want to use
And make sure you have the right access modifiers on the class and methods you want to use.
In my case I had a swift file I wanted to unit test, and the unit test file was also a swift class. I made sure the access modifiers were correct, but the statement
import stMobile
(let's say that stMobile is our target name)
still did not work (I was still getting the 'No such module' error), I checked my target, and its name was indeed stMobile. So, I went to Build Settings, under packaging, and found the Product Module Name, and for some reason this was called St_Mobile, so I changed my import statement
import St_Mobile
(which is the Product Module Name), and everything worked.
So, to sum up:
Check your Product Module Name and use the import statement below in you unit test class
import myProductModuleName
Make sure your access modifiers are correct (class level and your methods).
Instead of requiring explicit imports, the Swift compiler implicitly searches for .swiftmodule files of dependency Swift libraries.
Xcode can build swift modules for you, or refer to the railsware blog for command line instructions for swiftc.
As #high6 and #erik-p-hansen pointed out in the answer given by #high6, this can be overcome by importing the target for the module where the PrimeNumberModel class is, which is probably the same name as your project in a simple project.
While looking at this, I came across the article Write your first Unit Test in Swift on swiftcast.tv by Clayton McIlrath. It discusses access modifiers, shows an example of the same problem you are having (but for a ViewController rather than a model file) and shows how to both import the target and solve the access modifier problem by including the destination file in the target, meaning you don't have to make the class you are trying to test public unless you actually want to do so.

Conditional class import/ load

In a Groovy script is it possible to do a conditional import statement?
if (test){
import this.package.class
} else {
import that.package.class
}
The background to this is wanting to use something on MacOS 10.5 which only has JDK1.5 so one specific class is unavailable, but I have found someone who has written a back-port for it.
There is no way to conditionally import a class, but you can achieve something similar by attempting to load the class and then load another class if that one is not found.
Here's just an example:
def someClass
try {
someClass = "org.apache.webdavlib.WebdavFile" as Class
} catch (Exception ex) {
someClass = "java.io.File" as Class
}
def someInstance = someClass.newInstance("~/project/temp.log")
assert "java.io.File" == someInstance.getClass().getName()
Jochen "blackdrag" Theodorou proposed the following on the groovy user list a while ago:
wsh = this.class.classLoader.loadClass("org.codehaus.groovy.scriptom.ActiveXObject").newInstance("WScript.Shell")
Then you do not need to use the import statement.
Here is the thread on the mailing list
No, conditional imports are not supported... Best I can think of atm would be to use reflection as you would need to in java...
An ast transform could also be used here to tag the class and wrap the code that uses the missing class with the required reflection code
I guess a class loader could do the trick, but will be complicated.
Have you considered to use a shadow class and jsut deploy different jars?
Something like
//jdk 1.5
somethingelse extends this {
}
.
//jdk 1.6
somtheingelse extends that {
}
=> compile both to two different jar files, which you deploy on one system but not the other...
not perfect, but could work
...wait: if your libraries just differ in the package name, then you don't need a shadow class. Can't you move the one or the other in the same package?

Why does my Scala enumeration break when I move it to another package?

Enumeration code looks like the following
package com.mydomain
object Market extends Enumeration {
type Market = Value
val ASX, LSE = Value
}
I try to use as follows
import com.mydomain.Market._
.
.
.
if (Market.ASX == currentMarket) {
...
}
This was working when everything was in the same package. When I moved to a new package I now get
not found: value Market
If you import Market, you have ASX and LSE directly available to you. You don't have Market.ASX available--that would be if you had object Market available, which is what would happen if you did import com.mydomain._.
Being inside package com.mydomain causes com.mydomain._ to be loaded just like you imported it, so that's why you can say Market.ASX when you're in the same package.
When you write code in a different package, you need to either import com.mydomain._ and then use Market.ASX, or import com.mydomain.Market._ and then use ASX.