Can compile Scala programs but can't run them

2019-03-15 17:00发布

I am able to compile scala programs using scalac in terminal but I get the warning.

Charless-Macintosh:src Charles$ scalac hello.scala
Charless-Macintosh:src Charles$ scala HelloWorld
No such file or class on classpath: HelloWorld

Is this to do with .profile on scala. I'm pretty confused as to what is happening. Many thanks

3条回答
成全新的幸福
2楼-- · 2019-03-15 17:05

The problem is that you have set the CLASSPATH environment variable.

From > man scalac:

The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.

When you have the CLASSPATH variable set, scala will not include the current directory in its search, you must explicitly add it. This is why scala -cp . HelloWorld works.

To verify, perform echo CLASSPATH and it should give some non-empty string. Check your .bashrc/.zshrc files for any export CLASSPATH=... and remove these lines.

查看更多
一夜七次
3楼-- · 2019-03-15 17:12

The current directory is typically not in the classpath by default. So you need to give explicitly:

$ scala -cp . HelloWorld
查看更多
家丑人穷心不美
4楼-- · 2019-03-15 17:12

This was also happening to me but I think the better solution is to modify the CLASSPATH variable to include the current directory in addition to what you already had. e.g.

export CLASSPATH=.:$CLASSPATH

Now, you can simply use scala HelloWorld without that additional argument.

查看更多
登录 后发表回答