In my scala worksheet test.sc I define :
import com.tradedata.VolatilityInstance
test.sc exists at src/main/scala
In location src/main/scala I define :
package com.tradedata
class VolatilityInstance(intervalLength: Int, volatility: Double, beginDate: String, endDate: String) {
override def toString: String = {
this.beginDate
}
}
The filename for this class is VolatilityData.scala
VolatilityData.scala exists at level src/main/scala/com/tradedata
When I attempt to run the worksheet I receive error :
Error:(1, 16) object VolatilityInstance is not a member of package com.tradedata
import com.tradedata.VolatilityInstance
If i define a new Scala object :
import com.tradedata.VolatilityInstance
object Tester extends App {
}
Tester object runs without issue.
I've tried re-building the project, invalidating the caches and restarting IntelliJ but cannot fix.
Is this a bug with the Scala worksheet ? How to import other classes into the Scala worksheet ?
I've tested your case in IntelliJ IDEA 2019.2.3 (Ultimate Edition) with Scala plugin 2019.2.28
Open test.sc, click Scala worksheet settings and change Run type from REPL to Plain.
In Worksheet Settings check Build project before run
It helps me
Related
I am trying to run a scala project for the first time in eclipse. I have selected "Scala" in perspective. I am having trouble with configuring my run for scala.
My project name is scala_try and in the project folder I have:
src -> scala_try -> Demo.scala
When I right-click on Demo.scala and try to run it, I have:
Run As -> Run Configurations...
How do I configure my run for scala here?
I tried: Scala-Application -> New_configuration but when I search for Main Class, there is nothing matched.
If I just go on and write Demo as Main class, after running I get this error:
Error: Could not find or load main class Main
Caused by: java.lang.ClassNotFoundException: Main
my code in Demo.scala:
package scala_try
object Demo extends App{
def main(args: Array[String]) {
print("Hola!");
}
}
Any sort of help would be highly appreciated. Thanks in advance!
Just try removing either of these code
package scala_try
object Demo {
def main(args: Array[String]) {
print("Hola!");
}
}
OR
package scala_try
object Demo extends App{
print("Hola!");
}
Using extends App and main method together in a object generally causes this issue as per my opinion.
I've been tasked to update and write a series of tests on an app in Scala Play, a language and framework I'm unfamiliar with. Part of what I'd like to do is integrate the ScalaTestPlus library. To get started I have been following the following tutorial:
https://www.playframework.com/documentation/2.2.x/ScalaTestingWithScalaTest
Unfortunately I am not getting very far. I have added a new unit test file to the tests folder:
import org.scalatestplus.play._
class StackSpec extends PlaySpec {
"A Test" must {
"pass" in {
assert(1 == 1)
}
"Fail" in {
assert(1 != 1)
}
}
}
and I have updated my build.sbt to include the scalatestplus library
"org.scalatestplus" % "play_2.37" % "1.2.0" % "test"//,
Using Activator, I am trying to run my test file with test-only. Everything compiles without errors, but activator is not finding any tests
[info] No tests were executed.
I don't believe the issue is with activator, since I can run old test files (from the previous engineer) using the test and test-only commands. A quick sample of one of the previous (working) test files:
import java.util.concurrent.TimeUnit
import com.sun.xml.internal.bind.v2.TODO
import scala.collection.JavaConverters._
import controllers.Application
import models.{Item, PriorityBucket}
import play.api.test._
class WebSpec extends PlaySpecification {
"Home page" should {
"do something" in new WithSeleniumDbData(TestUtil.testApp) {
Redacted.deleteAll()
val ObId = TestUtil.create(Some(PriorityBucket.Low),
Some(Application.ENGLISH))
val item = Item.find(ItemId).get
browser.goTo("/")
browser.await().atMost(2,
TimeUnit.SECONDS).until(Selectors.all_obs).isPresent
}
Any ideas where I've gone astray? Thanks in advance for the help!
I am using scala 2.11
I am using play 2.3.7
EDIT: Possibly relevant, I switched the extension from PlaySpec to FlatSpec and saw the following error when compiling:
SampleSpec.scala:10: value in is not a member of String
[error] "pass" in {
I made sure to import FlatSpec as well, which has me a bit confused--is FlatSpec a member of ScalaTest but not a member of ScalaTestPlus, I don't see why else the compilation would fail.
UPDATE: To further investigate the issue I spun up a brand new Play app and copied over my sample test. After some tooling around with versions I've been able to get my test to run on the activator test command with the rest of the suite. Unfortunately, any other commands like test-only are still returning no tests run.
For those following I ran across the issue...the class name in this case needed to be identical to the file name, otherwise test-only cannot locate it.
I'm having some issues today with running a simple TestKit test in Intellij. The tests are for Scala code (I have the Scala plug-in for Intellij) and are based on Ray Roestenburg's example.
The Intellij project was created using a "Maven Module" which I then added all the dependencies to and created my project. The tests are located in the following place:
ActorBlast/src/test/scala/basicTest.scala
I'm basically "right-clicking" on the test and selecting "Run". What I get is the following error:
"C:\Program Files\Java\jdk1.7.0_25\bin\java" -Didea.launcher.port=7540...
Testing started at 2:29 PM ...
Unable to load a Suite class. This could be due to an error in your runpath.
Missing class: BasicActorSpec java.lang.ClassNotFoundException:
BasicActorSpec at
java.net.URLClassLoader$1.run(URLClassLoader.java:366) at
java.net.URLClassLoader$1.run(URLClassLoader.java:355) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:354) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
org.scalatest.tools.Runner$$anonfun$35.apply(Runner.scala:2393) at
org.scalatest.tools.Runner$$anonfun$35.apply(Runner.scala:2391) at
scala.collection.TraversableLike$$anonfun$filter$1.apply(TraversableLike.scala:264)
at scala.collection.immutable.List.foreach(List.scala:318) at
scala.collection.TraversableLike$class.filter(TraversableLike.scala:263)
at scala.collection.AbstractTraversable.filter(Traversable.scala:105)
at
org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:2391)
at
org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1006)
at
org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1005)
at
org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:2659)
at
org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1005)
at org.scalatest.tools.Runner$.run(Runner.scala:845) at
org.scalatest.tools.Runner.run(Runner.scala) at
org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:144)
at
org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 0
I can't figure out what this means. I've done a lot of searching but can't seem to find an answer. Note that the class the runner is complaining about not finding is the class I'm trying to test/run. The basicTest.scala looks like this:
// Testing specific imports
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{ShouldMatchers, WordSpecLike, BeforeAndAfterAll}
import akka.testkit.{TestKit, DefaultTimeout, ImplicitSender}
// Actor specific imports
import akka.actor.{ActorRef, Actor, ActorSystem, Props}
// Misc. needed imports
import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
// In order to run tests in this module you need to use JUnitRunner (as per scalatest.org)
#RunWith(classOf[JUnitRunner])
class BasicActorSpec extends TestKit(ActorSystem("BasicActorSpec", ConfigFactory.parseString(BasicActorSpec.config)))
with DefaultTimeout with ImplicitSender with WordSpecLike with ShouldMatchers with BeforeAndAfterAll {
import BasicActorSpec._
val echoRef = system.actorOf(Props[EchoActor])
val forwardRef = system.actorOf(Props[ForwardActor])
override def afterAll {
shutdown(system)
}
/**
* The actual tests...
*/
"An EchoActor" should {
"Respond with the same message it receives" in {
within(500 millis) {
echoRef ! "test"
expectMsg("test")
}
}
}
"A Forwarding Actor" should {
"Forward a message it receives" in {
within(500 millis) {
forwardRef ! "test"
expectMsg("test")
}
}
}
}
/**
* Companion object of test class
*/
object BasicActorSpec {
val config =
"""
|akka {
| loglevel = "Warning"
|}
""".stripMargin
/**
* Classes of Actors used in testing
*/
class EchoActor extends Actor {
def receive = {
case msg => sender ! msg
}
}
class ForwardActor(next: ActorRef) extends Actor {
def receive = {
case msg => next ! msg
}
}
}
Any help as to why I am getting this error would be GREATLY appreciated.
Run build the project - It helped me to resolve that issue that could have happened to me when I cleared Cache IDEA :) while trying to tackle another issue
This is how I solved same exception:
--> Right click on your project folder in IDE:
--> Click Add Framework Support
--> Then Check Scala
--> Click OK
My project already had the setup as mentioned by #Rustam Aliyev. Still was getting the same exception. Rebuilding the project did not help either. Quite weird ; but Restarting the IDE helped to solve the issue
This issue happened to me recently when I was trying to run tests in an inherited Scala project using IntelliJ IDEA 2018 (Community Edition). Below steps helped me to fix it:
File → Project Structure → {Choose specific module} → "Paths" tab → Select "Use module compile output path" → Modify "Test output path" to point to test-classes folder. For example:
Output path: /home/rustam/IdeaProjects/{project}/{module}/target/scala-2.12/classes
Test output path: /home/rustam/IdeaProjects/{project}/{module}/target/scala-2.12/test-classes
IntelliJ does not like multiple Scala classes defined in one file, so make sure the test class is named the same as the test file and nest other helper classes, which you can refactor later as necessary.
I met this issue when I used Gatling
I fix it by replacing gatling-classes to test-classes on File -> Project Structure -> Modules -> Module Name -> Paths -> Test output path
You need to set up the Scala SDK.
1.) Usually, intelliJ will ask you by showing a message on right hand corner of your editor
2.) You can do it by yourself as mentioned on the https://www.jetbrains.com/help/idea/discover-intellij-idea-for-scala.html
In my case, I was missing the Scala facet in my module.
https://blog.jetbrains.com/scala/2010/09/02/project-configuration-explained/
I got rid of the error once I configured module properly.
You can try to recompile the test classes:
sbt test:compile
If you are using IntelliJ to run scalatest make sure the class paths are correct. For example:
/dummyApp
your build.sbt should look like, name := "dummyApp". If you name it name := "dummy App" you will get errors.
In my case I had in Preferences -> Build, Execution, Deployment -> sbt
Use sbt shell for build and import checkbox enabled
And the test was not in the expected directory src/test but in src/it (integrated test).
I encountered the error when the test class was not part of any package.
I am using the multi maven module and tried all possibilities here but not able to fix this. But for me I closed the complete IntelliJ -> removed .idea folder -> deleted managed projects from recent projects window.-> reimport the project did the job.
This kind of thing keeps happening to me every now and then. All the more concrete suggestions above have merit. Another possibility (which worked this time for me): Edit the run configuration for your tests; click "Use sbt"; run the tests (this should have no problem since it's just using the sbt-shell to run the tests); now unselect "Use sbt" and try it. It worked for me.
Another one in the long list of checks, if you do not use unique test names you get this error without any hint, in a long test suite it is easier to miss.
Failed
test("Check thing 1") {
class TestClass1 extends MainClass1{
... }
test("Check thing 1") {
class TestClass2 extends MainClass2{
... }
Successful
test("Check thing 1") {
class TestClass1 extends MainClass1{
... }
test("Check thing 2") {
class TestClass2 extends MainClass2{
... }
I got the same message on Idea 2021.1. I tried all the ways above but what helped me is running Scala-tests via sbt like this:
sbt "; project nameOfProject; testOnly some.package.SomeTest"
After that I could debug the same tests via Idea.
I had two modules marked as Test Sources Root and thus it didn't like that. So I unmarked one and then it worked great
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
I'm developing an application on Eclipse with Scala and a would like to create a .jar. I have found tuto to do that, but it use the package scala.tools.nsc and I don't know where I can found this thing.
I have tried too, to generate the .class and then with the command jar cmf .... to generate the .jar but when I launch the .jar an error occur. (NoClassFound)
With sbt I have tried too, but when I compile my project that work with eclipse a lot of error appear.
Somebody can me explain how I can simply create a .jar with Eclipse or another tools.
Eclipse has a build-in option to generate runnable jars, but it is well hidden. Also it does not recognize Scala's main() signatures, so you will have to create a Java class with a main() method.
Create a Java class with a main() method which simply forwards the call to your Scala code.
Then right click on your newly created Java class and select: Run As -> Java Application.
This will create a runnable configuration which will later be used as a part of your runnable jar.
Now you are ready to dig out the runnable jar option from the Eclipse's menu:
File -> Export -> Java -> Runnable JAR file
In the presented dialog select the Launch Configuration you have created earlier (in step2), name your jar (myapp.jar), select your dependency export options and click finish.
The jar will be created in the Eclipse's workspace by default.
Run the jar using the line: scala myapp.jar
Your question about missing images: Eclipse requires a manual refresh when files are added or removed. Right click on your project and select Refresh.
This concludes the tutorial on the highly intuitive Eclipse interface.
Note: Instructions for Eclipse version 3.6.2.
Jars
When you create a jar out of your classes, possibly the dependencies are not included in that jar. When running that jar, you need to put the jars containing the dependencies on the classpath (with the -cp switch to java). Most important dependency is the scala-library jar. Of course knowing what is not found by NoClassDefFound would help.
Sbt
When building with sbt, maybe it is missing dependencies that you have manually added to the Eclipse project? (Note: I did not use sbt).
Maven
I found the clearest and most painless way is to go with maven alone, or possibly maven + Intellij Idea (community edition is free) + Scala Plugin. Works very smooth.
For maven, you need to adapt the available scala archetype a bit since the libraries it refers to are not the most recent version, but apart from that it is very fine.
Here is a pom.xml I'm using: https://gist.github.com/1096870
Use the standard maven folder structure (source root is src/main/scala) and then mvn package creates the jar fine.
Use the below steps for time being .But this is not the full time solution.Better to go for sbt build jar for Spark-Scala combination.
Temporary solution using java class ,calling the scala main class.
MainClass.java
public class MainClass {
public static void main(String[] args) {
SampleApp app=new SampleApp();
app.main(args); }
}
SampleApp.scala
class SampleApp {
def main(args: Array[String]) {
println("First Scala SampleApp")}
}
Export it as a jar by using normal java jar export by choosing the MainClass main method.
name the jar file as Sample.jar
Run it in the Cluster using below command.
/spark/bin/spark-submit --class com.scala.MainClass SampleScala.jar
The output you can get as:
First Scala SampleApp
% cat a.scala
package foo
object Whee {
def main(args: Array[String]): Unit = {
println("I'm in a jar")
}
}
% scalac29 -d whee.jar a.scala
% scala29 -cp whee.jar foo.Whee
I'm in a jar
%
To build off of what #Kumar Basapuram wrote:
Make a java class called "Wrapper.java".
package animals;
public class Wrapper {
public static void main(String[] args) {
SampleApp app=new SampleApp();
app.main(args);
}
}
Link this main method to the main method in the "SampleApp.scala" class.
package animals
class SampleApp {
def main(args: Array[String]){
var c = new Cow("Bessie", 100)
println(c.speak)
var h = new Horse("CJ", 50)
println(h.speak)
var s = new Sheep("Little Lamb", 25)
println(s.speak)
println(s.weigh)
println(h.weigh)
println(c.weigh)
}
}
Project with Java and Scala Classes Picture
Right Click on the Project ScalaPracticeCreation.
Click Export...
Click Runnable JAR file under the Java folder
Exporting Scala Class into a jar Executable Picture
Click Next >
Select Wrapper - ScalaPracticeCreations
Select Export destination to a place on your computer
Select "Extract required libraries into generated JAR" under the "Library
handling:" option
Click Finish
Run the file through the Eclipse IDE and it works.
Run it through the Command Prompt and it does not work.
Command Prompt Picture
To fix this remove the println methods from the "SampleApp.scala".
package animals
class SampleApp {
def main(args: Array[String]) {
var c = new Cow("Bessie", 100)
var h = new Horse("CJ", 50)
var s = new Sheep("Little Lamb", 25)
c.weigh().toString()
}
}
add "System.out.println(app.main(args));" to replace "app.main(args);" in the Wrapper.java class
package animals;
public class Wrapper {
public static void main(String[] args) {
SampleApp app=new SampleApp();
System.out.println(app.main(args));
}
}
Now reexport the program after running it.
success in the command prompt Picture
Now it works.
Here are the extra filler .scala classes. Note that the Demo.scala class is irrelevant.
Weight.scala:
package animals
abstract class Weight(size: Int) {
def weigh = "My size is " + size
}
Animal.scala:
package animals
abstract class Animal(name: String, weight: Int) extends Weight(weight){
def speak = name + " says " + sound
def sound: String
override def weigh() = "My name is " + name + " and I weigh: " + weight
}
Cow.scala:
package animals
class Cow (name: String, weight: Int) extends Animal(name,weight){
override def sound() = "mooooo"
}
Horse.scala:
package animals
class Horse (name: String, weight: Int) extends Animal(name,weight){
override def sound() = "neigh"
}
Sheep.scala:
package animals
class Sheep (name: String, weight: Int) extends Animal(name,weight) {
override def sound() = "baaaa"
}
Note that this may not be the best solution although it is a functional solution. Scala sbt may be a better solution: Scala sbt or this Scala sbt-assembly.