Scala Compiler Options

Language

Introduction

Scala compiler scalac offers various compiler options, also referred to as compiler flags, to change how to compile your program.

Nowadays, most people are not running scalac from the command line. Instead, they use sbt, an IDE, and other tools as their interface to the compiler. Therefore they may not even have scalac installed, and won’t think to do man scalac.

This page comes to the rescue for the people to find…

  • What compiler options scalac offers
  • How to use compiler options

How to use compiler options

Use compiler options with scalac

scalac [ <options> ] <source files>

E.g. scalac -encoding utf8 -Xfatal-warnings Hello.scala

Use compiler options with sbt

scalacOptions ++= Seq(
  "-encoding", "utf8", // Option and arguments on same line
  "-Xfatal-warnings",  // New lines for each options
  "-deprecation",
  "-unchecked",
  "-language:implicitConversions",
  "-language:higherKinds",
  "-language:existentials",
  "-language:postfixOps"
)

Standard Settings

A set of standard options that are supported on the current development environment and will be supported in future releases.

-classpath PATH or -cp PATH

Specify where to find user class files.

Default: .
-d DIRECTORY|JAR

destination for generated classfiles.

Default: .
-no-specialization

Ignore @specialize annotations.

-language:FEATURE1,FEATURE2

Enable or disable language features: _ for all, -language:help to list choices.

-language:dynamics

Allow direct or indirect subclasses of scala.Dynamic

-language:postfixOps

Allow postfix operator notation, such as 1 to 10 toList

-language:reflectiveCalls

Allow reflective access to members of structural types

-language:implicitConversions

Allow definition of implicit functions called views

-language:higherKinds

Allow higher-kinded types

-language:existentials

Existential types (besides wildcard types) can be written and inferred

-language:experimental.macros

Allow macro definition (besides implementation and application)

-release RELEASE

Compile for a specific version of the Java platform. Supported targets: 6, 7, 8, 9

-optimise or -optimize

Compiler flag for the optimizer in Scala 2.11

value-overrides

Generated value class method overrides an implementation.

-bootclasspath PATH

Override location of bootstrap class files.

Default: Defaults.scalaBootClassPath
-extdirs PATH

Override location of installed extensions.

Default: Defaults.scalaExtDirs
-javabootclasspath PATH

Override java boot classpath.

Default: Defaults.javaBootClassPath
-javaextdirs PATH

Override java extdirs classpath.

Default: Defaults.javaExtDirs
-sourcepath PATH

Specify location(s) of source files.

-dependencyfile FILE

Set dependency tracking file.

Default: .scala_dependencies
-deprecation

Emit warning and location for usages of deprecated APIs.

-encoding ENCODING

Specify character encoding used by source files.

Default: Properties.sourceEncoding
-explaintypes

Explain type errors in more detail.

-feature

Emit warning and location for usages of features that should be imported explicitly.

-g:LEVEL

Set level of generated debugging info. Choices: (none,source,line,vars,notailcalls), default: vars.

Default: vars
-g:none
-g:source
-g:line
-g:vars
-g:notailcalls
-help

Print a synopsis of standard options

-nowarn

Generate no warnings.

-print

Print program with Scala-specific features removed.

-target:TARGET

Target platform for object files. All JVM 1.5 - 1.7 targets are deprecated. Choices: (jvm-1.5,jvm-1.6,jvm-1.7,jvm-1.8), default: jvm-1.8.

Default: jvm-1.8
-target:jvm-1.5
-target:jvm-1.6
-target:jvm-1.7
-target:jvm-1.8
-unchecked

Enable additional warnings where generated code depends on assumptions.

-uniqid

Uniquely tag all identifiers in debugging output.

-usejavacp

Utilize the java.class.path in classpath resolution.

-usemanifestcp

Utilize the manifest in classpath resolution.

-verbose

Output messages about what the compiler is doing.

-version

Print product version and exit.

JVM Settings

Settings influencing the runtime system.

-Jflag

Pass flag directly to the runtime system.

-Dproperty=value

Pass -Dproperty=value directly to the runtime system.

-nobootcp

Do not use the boot classpath for the scala jars.

Plugin Settings

-P PLUGIN:OPT1,PLUGIN:OPT2

Pass an option to a plugin

Note: If you use sbt, compiler plugins support may be useful.

Advanced Settings

Options that starts with -X are maybe renamed or removed in future releases.

-X

Print a synopsis of advanced options.

-Xcheckinit

Wrap field accessors to throw an exception on uninitialized access.

-Xdev

Indicates user is a developer - issue warnings about anything which seems amiss

-Xdisable-assertions

Generate no assertions or assumptions.

-Xelide-below ARG

Calls to @elidable methods are omitted if method priority is lower than argument

Default: Int.MinValue
-Xno-forwarders

Do not generate static forwarders in mirror classes.

-Xgenerate-phase-graph FILE

Generate the phase graphs (outputs .dot files) to fileX.dot.

-Xlog-implicits

Show more detail on why some implicits are not applicable.

-Xlog-implicit-conversions

Print a message whenever an implicit conversion is inserted.

-Xlog-reflective-calls

Print a message when a reflective method call is generated

-Xlog-free-terms

Print a message when reification creates a free term.

-Xlog-free-types

Print a message when reification resorts to generating a free type.

-Xmax-classfile-name ARG

Maximum filename length for generated classes

Default: 255
Min: 72
Max: 255
-Xmaxerrs ARG

Maximum errors to print

Default: 100
-Xmaxwarns ARG

Maximum warnings to print

Default: 100
-Xmigration VERSION

Warn about constructs whose behavior may have changed since version.

Default: none
-Xno-uescape

Disable handling of \u unicode escapes.

-Xnojline

Do not use JLine for editing.

-Xverify

Verify generic signatures in generated bytecode.

-Xplugin PATHS1,PATHS2

Load a plugin from each classpath.

-Xplugin-disable PLUGIN1,PLUGIN2

Disable plugins by name.

-Xplugin-list

Print a synopsis of loaded plugins.

-Xplugin-require PLUGIN1,PLUGIN2

Abort if a named plugin is not loaded.

-Xpluginsdir PATH

Path to search for plugin archives.

Default: Defaults.scalaPluginPath
-Xprint ARG

Print out program after phases

Note: See Compilation Phases
-Xprint-pos

Print tree positions, as offsets.

-Xprint-types

Print tree types (debugging option).

-Xprint-args

Print all compiler arguments and exit.

-Xprompt

Display a prompt after each error (debugging option).

-Xresident

Compiler stays resident: read source filenames from standard input.

-Xscript OBJECT

Treat the source file as a script and wrap it in a main method.

-Xmain-class PATH

Class for manifest’s Main-Class entry (only useful with -d jar)

-Xshow-class CLASS

Show internal representation of class.

-Xshow-object OBJECT

Show internal representation of object.

-Xshow-phases

Print a synopsis of compiler phases.

-Xsource-reader CLASSNAME

Specify a custom method for reading source files.

-Xreporter CLASSNAME

Specify a custom reporter for compiler messages.

Default: scala.tools.nsc.reporters.ConsoleReporter
-Xstrict-inference

Don’t infer known-unsound types

-Xsource VERSION

Treat compiler input as Scala source for the specified version, see scala/bug#8126.

Default: 2.12.0
-Xno-patmat-analysis

Don’t perform exhaustivity/unreachability analysis. Also, ignore @switch annotation.

-Xfull-lubs

Retains pre 2.10 behavior of less aggressive truncation of least upper bounds.

-Xmixin-force-forwarders:MODE

Generate forwarder methods in classes inhering concrete methods from traits. Default: true, help to list choices.

Default: true
-Xmixin-force-forwarders:true

Always generate mixin forwarders.

-Xmixin-force-forwarders:junit

Generate mixin forwarders for JUnit-annotated methods (JUnit 4 does not support default methods).

-Xmixin-force-forwarders:false

Only generate mixin forwarders required for program correctness.

-Xxml:PROPERTY1,PROPERTY2

Configure XML parsing.: _ for all, -Xxml:help to list choices.

-Xxml:coalescing

Convert PCData to Text and coalesce sibling nodes

-Xfuture

Turn on future language features.

-Xexperimental
Deprecated: For in Scala 2.12 and earlier. In 2.13 all options previously enabled by -Xexperimental are enabled by default or removed.

Enable experimental extensions.

-Xmacro-settings OPTION1,OPTION2

Custom settings for macros.

Private Settings

Options with -Y prefix are more experimental and unstable than those with -X prefix.

Some without -Y prefix (e.g. -opt:** and -opt-inline-from) are also included, since such granular optimization-related options are changeable.

Those influencing to language semantics are likely to be deprecated in Scala 2.13 (see scala/scala-dev#430).

-Y

Print a synopsis of private options.

-Yoverride-objects

Allow member objects to be overridden.

-Yoverride-vars

Allow vars to be overridden.

-Ybreak-cycles

Attempt to break cycles encountered during typing

-Ybrowse ARG

Browse the abstract syntax tree after phases

Note: See Compilation Phases
-Ycheck ARG

Check the tree at the end of phases

Note: See Compilation Phases
-Yshow ARG

(Requires -Xshow-class or -Xshow-object) Show after phases

Note: See Compilation Phases
-Ycompact-trees

Use compact tree printer when displaying trees.

-Yno-completion

Disable tab-completion in the REPL.

-Ydebug

Increase the quantity of debugging output.

-Yresolve-term-conflict:STRATEGY

Resolve term conflicts. Choices: (package,object,error), default: error.

Default: error
-Yresolve-term-conflict:package
-Yresolve-term-conflict:object
-Yresolve-term-conflict:error
-Ylog ARG

Log operations during phases

-Ylog-classpath

Output information about what classpath is being applied.

-Yno-generic-signatures

Suppress generation of generic signatures for Java.

-Yno-imports

Compile without importing scala., java.lang., or Predef.

-Yno-predef

Compile without importing Predef.

-Yno-adapted-args

Do not adapt an argument list (either by inserting () or creating a tuple) to match the receiver.

-Yrecursion ARG

Set recursion depth used when locking symbols.

Default: 0
Min: 0
Max: 2147483647
-Yshow-trees

(Requires -Xprint:) Print detailed ASTs in formatted form.

-Yshow-trees-compact

(Requires -Xprint:) Print detailed ASTs in compact form.

-Yshow-trees-stringified

(Requires -Xprint:) Print stringifications along with detailed ASTs.

-Yshow-syms

Print the AST symbol hierarchy after each phase.

-Yshow-symkinds

Print abbreviated symbol kinds next to symbol names.

-Yshow-symowners

Print owner identifiers next to symbol names.

-Yskip ARG

Skip phases

Note: See Compilation Phases
-Ygen-asmp DIR

Generate a parallel output directory of .asmp files (ie ASM Textifier output).

-Ydump-classes DIR

Dump the generated bytecode to .class files (useful for reflective compilation that utilizes in-memory classloaders).

-Ystop-after ARG or -stop ARG

Stop after phases

Note: See Compilation Phases
-Ystop-before ARG

Stop before phases

Note: See Compilation Phases
-Yrangepos

Use range positions for syntax trees.

-Yvalidate-pos ARG

Validate positions after the given phases (implies -Yrangepos)

Note: -Yrangepos is enabled at the same time.
-Yshow-member-pos OUTPUT STYLE

Show start and end positions of members (implies -Yrangepos)

Note: -Yrangepos is enabled at the same time.
-Yreify-copypaste

Dump the reified trees in copypasteable representation.

-Ymacro-expand:POLICY

Control expansion of macros, useful for scaladoc and presentation compiler. Choices: (normal,none,discard), default: normal.

Default: normal
-Ymacro-expand:normal
-Ymacro-expand:none
-Ymacro-expand:discard
-Ymacro-no-expand
Deprecated: Use -Ymacro-expand:none instead.

Don’t expand macros. Might be useful for scaladoc and presentation compiler, but will crash anything which uses macros and gets past typer.

-Yrepl-sync

Do not use asynchronous code for repl startup

-Yrepl-class-based

Use classes to wrap REPL snippets instead of objects

-Yrepl-outdir PATH

Write repl-generated classfiles to given output directory (use “” to generate a temporary dir)

-Yinfer-argument-types

Infer types for arguments of overridden methods.

-YdisableFlatCpCaching

Do not cache flat classpath representation of classpath elements from jars across compiler instances.

-Ycache-plugin-class-loader:POLICY

Policy for caching class loaders for compiler plugins that are dynamically loaded. Default: none, help to list choices.

Default: none
-Ycache-plugin-class-loader:none

Don’t cache class loader

-Ycache-plugin-class-loader:last-modified

Cache class loader, using file last-modified time to invalidate

-Ycache-macro-class-loader:POLICY

Policy for caching class loaders for macros that are dynamically loaded. Default: none, help to list choices.

Default: none
-Ycache-macro-class-loader:none

Don’t cache class loader

-Ycache-macro-class-loader:last-modified

Cache class loader, using file last-modified time to invalidate

-Ypartial-unification

Enable partial unification in type constructor inference

-Yvirtpatmat

Enable pattern matcher virtualization

-Yexpose-empty-package

Internal only: expose the empty package.

-Ydelambdafy:STRATEGY

Strategy used for translating lambdas into JVM code. Choices: (inline,method), default: method.

Default: method
-Ydelambdafy:inline
-Ydelambdafy:method
-Ybackend-parallelism ARG

maximum worker threads for backend

Default: 1
Min: 1
Max: 16
-Ybackend-worker-queue ARG

backend threads worker queue size

Default: 0
Min: 0
Max: 1000
-Yjar-compression-level ARG

compression level to use when writing jar files

Default: -1
Min: -1
Max: 9
-opt:OPTIMIZATION1,OPTIMIZATION2

Enable optimizations: _ for all, -opt:help to list choices.

Note: if inline not contained and either l:project or l:classpath are contained, then l:inline is enabled.
-opt:unreachable-code

Eliminate unreachable code, exception handlers guarding no instructions, redundant metadata (debug information, line numbers).

-opt:simplify-jumps

Simplify branching instructions, eliminate unnecessary ones.

-opt:compact-locals

Eliminate empty slots in the sequence of local variables.

-opt:copy-propagation

Eliminate redundant local variables and unused values (including closures). Enables unreachable-code.

-opt:redundant-casts

Eliminate redundant casts using a type propagation analysis.

-opt:box-unbox

Eliminate box-unbox pairs within the same method (also tuples, xRefs, value class instances). Enables unreachable-code.

-opt:nullness-tracking

Track nullness / non-nullness of local variables and apply optimizations.

-opt:closure-invocations

Rewrite closure invocations to the implementation method.

-opt:inline

Inline method invocations according to -Yopt-inline-heuristics and -opt-inline-from.

-opt:l:none

Disable optimizations. Takes precedence: -opt:l:none,+box-unbox / -opt:l:none -opt:box-unbox don`t enable box-unbox.

-opt:l:default

Enable default optimizations: unreachable-code.

-opt:l:method

Enable intra-method optimizations: unreachable-code,simplify-jumps,compact-locals,copy-propagation,redundant-casts,box-unbox,nullness-tracking,closure-invocations.

-opt:l:inline

Enable cross-method optimizations (note: inlining requires -opt-inline-from): l:method,inline.

-opt:l:project
Deprecated: Use -opt:l:inline -opt-inline-from instead.

[deprecated, use -opt:l:inline, -opt-inline-from] Enable cross-method optimizations within the current project.

-opt:l:classpath
Deprecated: Use -opt:l:inline -opt-inline-from instead.

[deprecated, use -opt:l:inline, -opt-inline-from] Enable cross-method optimizations across the entire classpath.

-opt-inline-from PATTERNS1,PATTERNS2

Patterns for classfile names from which to allow inlining, help for details.

-Yopt-inline-heuristics:STRATEGY

Set the heuristics for inlining decisions. Choices: (at-inline-annotated,everything,default), default: default.

Default: default
-Yopt-inline-heuristics:at-inline-annotated
-Yopt-inline-heuristics:everything
-Yopt-inline-heuristics:default
-opt-warnings:WARNING1,WARNING2

Enable optimizer warnings: _ for all, -opt-warnings:help to list choices.

-opt-warnings:none

No optimizer warnings.

-opt-warnings:at-inline-failed-summary

One-line summary if there were @inline method calls that could not be inlined.

-opt-warnings:at-inline-failed

A detailed warning for each @inline method call that could not be inlined.

-opt-warnings:any-inline-failed

A detailed warning for every callsite that was chosen for inlining by the heuristics, but could not be inlined.

-opt-warnings:no-inline-mixed

In mixed compilation, warn at callsites methods defined in java sources (the inlining decision cannot be made without bytecode).

-opt-warnings:no-inline-missing-bytecode

Warn if an inlining decision cannot be made because a the bytecode of a class or member cannot be found on the compilation classpath.

-opt-warnings:no-inline-missing-attribute

Warn if an inlining decision cannot be made because a Scala classfile does not have a ScalaInlineInfo attribute.

-Yopt-trace PACKAGE/CLASS.METHOD

Trace the optimizer progress for methods; _ to print all, prefix match to select.

-Yopt-log-inline PACKAGE/CLASS.METHOD

Print a summary of inliner activity; _ to print all, prefix match to select.

-Ystatistics ARG

Print compiler statistics for specific phases phases (default: parser,typer,patmat,erasure,cleanup,jvm)

Default: parser,typer,patmat,erasure,cleanup,jvm
Note: See Compilation Phases
-Yhot-statistics-enabled

Enable -Ystatistics to print hot statistics.

-Yprofile-enabled

Enable profiling.

-Yprofile-destination FILE

where to send profiling output - specify a file, default is to the console.

Note: -Yprofile-enabled is enabled at the same time.
-Yprofile-external-tool ARG

Enable profiling for a phase using an external tool hook. Generally only useful for a single phase phases (default: typer)

Default: typer
Note: -Yprofile-enabled is enabled at the same time.
-Yprofile-run-gc ARG

Run a GC between phases - this allows heap size to be accurate at the expense of more time. Specify a list of phases, or all phases (default: _)

Default: _
Note: -Yprofile-enabled is enabled at the same time.
-Ydoc-debug

Trace all scaladoc activity.

-Yide-debug

Generate, validate and output trees using the interactive compiler.

-Yissue-debug

Print stack traces when a context issues an error.

-Ymacro-debug-lite

Trace essential macro-related activities.

-Ymacro-debug-verbose

Trace all macro-related activities: compilation, generation of synthetics, classloading, expansion, exceptions.

-Ypos-debug

Trace position validation.

-Yreify-debug

Trace reification.

-Ytyper-debug

Trace all type assignments.

-Ypatmat-debug

Trace pattern matching translation.

-Ypatmat-exhaust-depth ARG

off

Default: 20
Min: 10
Max: 2147483647
-Yquasiquote-debug

Trace quasiquote-related activities.

Warning Settings

This section assembles the -X and -Y options those influence the printing of warnings.

-Xfatal-warnings

Fail the compilation if there are any warnings.

-Ywarn-macros:MODE

Enable lint warnings on macro expansions. Default: before, help to list choices.

Default: before
-Ywarn-macros:none

Do not inspect expansions or their original trees when generating unused symbol warnings.

-Ywarn-macros:before

Only inspect unexpanded user-written code for unused symbols.

-Ywarn-macros:after

Only inspect expanded trees when generating unused symbol warnings.

-Ywarn-macros:both

Inspect both user-written code and expanded trees when generating unused symbol warnings.

-Ywarn-dead-code

Warn when dead code is identified.

-Ywarn-value-discard

Warn when non-Unit expression results are unused.

Note: To reduce noises for common idiom, warning are suppressed if type of results are this.type.
-Ywarn-numeric-widen

Warn when numerics are widened.

-Ywarn-unused:WARNING1,WARNING2

Enable or disable specific unused warnings: _ for all, -Ywarn-unused:help to list choices.

-Ywarn-unused:imports

Warn if an import selector is not referenced.

-Ywarn-unused:patvars

Warn if a variable bound in a pattern is unused.

-Ywarn-unused:privates

Warn if a private member is unused.

-Ywarn-unused:locals

Warn if a local definition is unused.

-Ywarn-unused:explicits

Warn if an explicit parameter is unused.

-Ywarn-unused:implicits

Warn if an implicit parameter is unused.

-Ywarn-unused:params

Enable -Ywarn-unused:explicits,implicits.

-Ywarn-unused:linted

-Xlint:unused.

-Ywarn-extra-implicit

Warn when more than one implicit parameter section is defined.

-Ywarn-self-implicit

Warn when an implicit resolves to an enclosing self-definition.

-Xlint:WARNING1,WARNING2

Enable or disable specific warnings: _ for all, -Xlint:help to list choices.

Note: If this options contains unused, it enables -Ywarn-unused:linted. Otherwise it disables -Ywarn-unused:linted.
-Xlint:adapted-args

Warn if an argument list is modified to match the receiver.

Note: Alias is -Ywarn-adapted-args.
-Xlint:nullary-unit

Warn when nullary methods return Unit.

Note: Alias is -Ywarn-nullary-unit.
-Xlint:inaccessible

Warn about inaccessible types in method signatures.

Note: Alias is -Ywarn-inaccessible.
-Xlint:nullary-override

Warn when non-nullary def f() overrides nullary def f.

Note: Alias is -Ywarn-nullary-override.
-Xlint:infer-any

Warn when a type argument is inferred to be Any.

Note: Alias is -Ywarn-infer-any.
-Xlint:missing-interpolator

A string literal appears to be missing an interpolator id.

-Xlint:doc-detached

A Scaladoc comment appears to be detached from its element.

-Xlint:private-shadow

A private field (or class parameter) shadows a superclass field.

-Xlint:type-parameter-shadow

A local type parameter shadows a type already in scope.

-Xlint:poly-implicit-overload

Parameterized overloaded implicit methods are not visible as view bounds.

-Xlint:option-implicit

Option.apply used implicit view.

-Xlint:delayedinit-select

Selecting member of DelayedInit.

-Xlint:by-name-right-associative

By-name parameter of right associative operator.

-Xlint:package-object-classes

Class or object defined in package object.

-Xlint:unsound-match

Pattern match may not be typesafe.

-Xlint:stars-align

Pattern sequence wildcard must align with sequence component.

-Xlint:constant

Evaluation of a constant arithmetic expression results in an error.

-Xlint:unused

Enable -Ywarn-unused:imports,privates,locals,implicits.

IDE Specific Settings

-Ypresentation-verbose

Print information about presentation compiler tasks.

-Ypresentation-debug

Enable debugging output for the presentation compiler.

-Ypresentation-any-thread

Allow use of the presentation compiler from any thread

-Ypresentation-strict

Do not report type errors in sources with syntax errors.

-Ypresentation-log FILE

Log presentation compiler events into file

-Ypresentation-replay FILE

Replay presentation compiler events from file

-Ypresentation-delay ARG

Wait number of ms after typing before starting typechecking

Default: 0
Min: 0
Max: 999

Additional resources

Compilation Phases

initial
initializing compiler
parse
parse source files
namer
create symbols
analyze
name and type analysis
refcheck
reference checking
uncurry
uncurry function types and applications
lambdalift
lambda lifter
typesasvalues
represent types as values
addaccessors
add accessors for constructor arguments
explicitouterclasses
make links from inner classes to enclosing one explicit
addconstructors
add explicit constructor for each class
tailcall
add tail-calls
wholeprog
perform whole program analysis
addinterfaces
add one interface per class
expandmixins
expand mixins by code copying
boxing
makes boxing explicit
erasure
type eraser
icode
generate icode
codegen
enable code generation
terminal
compilation terminated
all
matches all phases

Contributors to this page: