Scala -- not a member of package - scala

I am learning Scala so bear with me if this is a stupid question.
I have this package and a class (teared it down to most simplistic version):
package Foo {
class Bar {}
}
then in main.scala file I have:
import Foo.Bar
object test {
def main() {
val b = new Bar()
}
}
Why am I getting this:
test.scala:1: error: Bar is not a member of Foo
It points at the import statement.

scalac is the scala compiler. Foo.bar needs to have been compiled for you to use it, so you can't just run your main.scala as a script.
The other mistake in your code is that the main method needs to be
def main(args: Array[String]) { ...
(or you could have test extends App instead and do away with the main method).
I can confirm if you put the two files above in an empty directory (with the correction on the main method signature) and run scalac * followed by scala test it runs correctly.

The most likely explanation is that you did not compile the first file, or you are doing something wrong when compiling. Let's say both files are in the current directory, then this should work:
scalac *.scala
It should generate some class files in the current directory, as well as a Bar.class file in the Foo directory, which it will create.

To quickly test a scala code in IntelliJ (with the Scala plugin), you can simply type Ctrl+Shift+F10:
Note that for testing a Scala class, you have other choices, also supported in IntelliJ:
JUnit or TestNG
ScalaTest

Related

Object pythagorean is not a member of package com - Scala programming error

I am working through Atomic Scala 2.0, learning Scala. I am trying to create a package myself and trying to use it in my programs. This is the code for creating my package:
package com.atomicscala.pythagorean
class RightTriangle {
def hypotenuse(a:Double, b:Double):Double={
math.sqrt(a*a + b*b)
}
def area(a:Double, b:Double):Double={
a*b/2
}
}
And this is my program:
import com.atomicscala.pythagorean._
object test{
def main(args:Array[String])={
val rt = new RightTriangle
println(rt.hypotenuse(3,4))
}
}
When I try to run my program after compiling the package, I get an error like this:
error: object pythagorean is not a member of package com.atomicscala
Instead, if I name the package as just pythogorean, the code works fine. what is causing this?
Try it with the package spelled correctly:
You have:
package com.atmoicscala.pythagorean
probably should be
package com.atomicscala.pythagorean
I was able to solve it by mentioning the Classpath in the Scala command.
scala filename -classpath . (If the package is in the current working
directory)
scala filename -classpath PackageLocation
The root cause is on the "fsc", fsc will reset when classpath change.
You may reset it explicitly by execute the following
fsc -reset
then you don't need to include -classpath in your scala command.
note: I am not sure whether this is a good practice.
Another way is to run the scala command without using the fsc offline compiler
scala -nc filename

Compile scala code mix with java code

I need to compile a scala code which calls a java code from it.
What I did:
1]I have a scala main file check.scala
package com.code
class check {
var Rectvalue = Array.ofDim[Int](5)
val str = Array.ofDim[String](1)
def nativeacces(arg: String, loop: Integer) {
val test = new testing()
test.process(arg, Rectvalue,str)
}
}
2.For creating instance val test = new testing() ,i added two .class(sample.class,testJNI.class) file from java source code inside the folder(package) com/code.
3.When I compile the scala code using
scalac check.scala
It generates the class file for the scala file.
What I have to do:
1.Instead of .class(sample.class,testJNI.class) file added inside the package ,i need to add jar file.
2.I tried, created jar file for the .class file and compile the Scala, it shows the error:
scala:6: error: not found: type testing
val test = new testing()
3.I need to link the .jar file and compile the scala main file
You can reference classes/directories/JARs via classpath option:
scalac -classpath your.jar check.scala
Related question: Adding .jar's to classpath (Scala).
If you want a proper build use SBT, put your JAR in lib directory in the root of project and it will figure out what to do for you. Here is Hello World of SBT.

What is the difference between scala classes, scripts and worksheets in Intellij-idea?

I'm using Intellij-idea for scala programming (with sbt plugin).
I want to know what is the difference between scala classes, scala scripts and scala worksheets. When we use each of them?
This will be very nice if you can explain it by a simple example.
Thanks
You have different ways of running scala code:
First create a Program with your classes, this is as in java, I use object because it works well without instantianing, like static, just compile with the SBT and run it you can also use the scala Interpreter REPL
We can use this object in the REPL
scala> object Hello {
| def main(args:Array[String]) {
| println("Hello, Scala !!")
| }
| }
defined object Hello
scala> Hello.main(Array("onlyforwork"))
Hello, Scala !!
compiling and running it using activator/SBT
> compile
[info] Compiling 1 Scala source to /home/anquegi/Dev/StackOverFlow/scalaStack/target/scala-2.11/classes...
[success] Total time: 2 s, completed 13/04/2015 11:29:42
> run
[warn] Multiple main classes detected. Run 'show discoveredMainClasses' to see the list
Multiple main classes detected, select one to run:
[1] org.example.Hello
[2] org.example.ScheduledTaskScala
[3] question1.Ques
[4] scriptworksheet.Hello
Enter number: 4
[info] Running scriptworksheet.Hello
Hello, Scala !!
[success] Total time: 19 s, completed 13/04/2015 11:30:04
The second is that if we add the scala code as a script or file Hello.scala, You can save your scala code in the file with .scala extension (basically with any file extension but prefered .scala extension) and to run, provide file name with extension as parameter to scala interpreter
/**
* Created by anquegi on 13/04/15.
*/
println("Hello, Scala !!")
if we call the scala interpreter this file is executed, you do not need to instanciate objects or clases, just executing like a shell script, you can also execute directlyy from Intellij, but I use the console with scala installed on the system
[anquegi#localhost scalaStack]$ scala src/main/scala/scriptworksheet/HelloScript.scala
Hello, Scala !!
And finally the worksheet is the most powerfull, I recommend this for increasing your prodductivity at work bacause it is easy to test things is like the REPL, ant it evluates the scala exprssions and shows you back the result
Following is excerpt from official github repo wiki about the scala worksheet
A worksheet is a Scala file that is evaluated on save, and the result of each expression is shown in a column to the right of your program. Worksheets are like a REPL session on steroids, and enjoy 1st class editor support: completion, hyperlinking, interactive errors-as-you-type, auto-format, etc.
// We can define objects or classes and the worksheet
//will print the sesult of every expression
object Hello {
def main(args:Array[String]) {
println("Hello, Scala !!")
}
}
println("Hello Scala")
val a = 4 + 5
the result
defined module Hello
Hello Scala
res0: Unit = ()
a: Int = 9
then a capture that shows you working with classe the work sheet and the console for scriptsin the Intellij
Scala Worksheet
It's the same as Scala Interpreter (REPL) but runs inside IntelliJ. Where you may easily and quickly evaluate some expressions. Check IntelliJ confluence page for more information.
Scala Script
If you don't want write script on Bash you can do it with Scala. It's just sequence of Scala statements.
Example:
import java.nio.file.{Paths, Files}
val ScalaSource = "*.scala"
val Path = "path/to/necessary/folder"
val stream = Files.newDirectoryStream(Paths.get(Path), ScalaSource)
val paths = stream.iterator
while (paths.hasNext) {
println(paths.next.getFileName)
}
Running it:
$ scala scala_script_name.scala
To getting started pick up this guide.
Classes & Object
Short answer for Scala classes it's similar to POJO and Scala Objects it's a Java Singleton class.

Why the "hello, world" is not output to the console?

I'm just learning scala, and I wrote the "hello,world" program like this:
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}
I saved it to a file named "helloworld.scala"
Now I run it in the console:
scala helloworld.scala
But nothing outputed. I thought it will output "Hello, world". Why?
PS
If I modify the content to:
println("Hello, world")
and run again, it will output "hello,world".
if you want to run your code as a script (by using scala helloworld.scala) you have to tell scala where your main method is by adding the line
HelloWorld.main(args)
to your code
the second option you have is compiling the script by using scalac helloworld.scala
and then calling the compiled version of your class using scala HelloWorld
You have two options.
Compile and Run:
As in Java you should have a main-method as a starting point of you application. This needs to be compiled with scalac. After that the compiled class file can be started with scala ClassName
scalac helloworld.scala
scala HelloWorld
Script:
If you have a small script only, you can directly write code into a file and run it with the scala command. Then the content of that file will be wrapped automagically in a main-method.
// hello.scala, only containing this:
println("Hello, world!")
then run it:
scala hello.scala
Anyway I would recomment to compile and run. There are some things, that are not possible in a "Scalascript", which I do not remember right now.

Scala, importing class

I have two files:
logic.scala and main.scala
logic.scala contains one class and main.scala have one class with method main (to run it). And I want to import a class from logic.scala and use this class to create object(s) and work with them.
How to import and compile it in proper way?
logic.scala code
package logic
class Logic{
def hello = "hello"
}
main.scala code
package runtime
import logic.Logic // import
object Main extends Application{
println(new Logic hello) // instantiation and invocation
}
compile the files with scalac
scalac *.scala
run your application with scala
scala -cp . runtime.Main