4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala source code compatible with both scala/scalac

Last updated at Posted at 2014-10-16

scala/scalac両対応なScalaソース

This is the defacto standard of executable Scala script, using shebang (little bit verbose for explanation below).
これは 実行可能な Scalaソースの標準です。本来不要なobjectとか付いていますが以下の説明のためです。

#!/usr/bin/env scala
!#
object hello extends App{
	println("Hello World");
}
hello.main(args)

Note: !# does not seem to be required if your Scala is 2.10(?)
2.10では!#は不要なようです(?)。

Actually hello.main(args) is verbose. Because (cited from scala -help:

A file argument will be run as a scala script unless it contains only
self-contained compilation units (classes and objects) and exactly one
runnable main method.  In that case the file will be compiled and the
main method invoked.  This provides a bridge between scripts and standard
scala source.

So let's strip it.
hello.main(args)は不要なので取り除きましょう。

#!/usr/bin/env scala
!#
object hello extends App{
	println("Hello World");
}

Now the scala command is dumb. We need explicit main method. Unfortunately App trait cannot be used.
scalaコマンドは何も出力しなくなってしまいました。mainメソッドを明示しなければなりません。残念ながらApp traitは使えないのです。

#!/usr/bin/env scala
!#
object hello{
	def main(args: Array[String]){
		println("Hello World");
	}
}

Finally, to satisfy scalac, let's use http://qiita.com/ando-masaki/items/323c6b08e07ec4538c3d trick (//usr/bin/env go run $0 $@;exit).
scalacを満足させるため、「Go言語でshebang」のトリックを使います。

//usr/bin/env scala $0 $@;exit
object hello{
	def main(args: Array[String]){
		println("Hello World");
	}
}

Great. Now this source is compatible with both scala/scalac.
素晴らしい!このソースはscala/scalac互換になりました。

Finally, don't forget that there must be only one class/object or this trick won't work anymore.
最後に、このトリックを使うにはclass/objectは複数置けないことに留意してください。


I have found that similar technique can be applied to F#.
Make the file extention .fsx and make the first line //usr/bin/env fsharpi $0 $@;exit.

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?