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.

-Dproperty=value

Pass -Dproperty=value directly to the runtime system.

-J<flag>

Pass flag directly to the runtime system.

-P PLUGIN:OPT1,PLUGIN:OPT2

Pass an option to a plugin

-X

Print a synopsis of advanced options.

-Y

Print a synopsis of private options.

-bootclasspath PATH

Override location of bootstrap class files.

-classpath PATH or -cp PATH

Specify where to find user class files.

Default: .
-d DIRECTORY|JAR

destination for generated classfiles.

Default: .
-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: UTF-8
-explaintypes

Explain type errors in more detail.

-extdirs PATH

Override location of installed extensions.

-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

-javabootclasspath PATH

Override java boot classpath.

Default: /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/resources.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jsse.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jce.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/charsets.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfr.jar:/usr/lib/jvm/java-8-openjdk-amd64/jre/classes
-javaextdirs PATH

Override java extdirs classpath.

Default: /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext:/usr/java/packages/lib/ext
-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)

-no-specialization

Ignore @specialize annotations.

-nobootcp

Do not use the boot classpath for the scala jars.

-nowarn

Generate no warnings.

-opt:OPTIMIZATION1,OPTIMIZATION2

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

-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] Enable cross-method optimizations within the current project.

-opt:l:classpath

[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.

-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.

-optimise or -optimize

Compiler flag for the optimizer in Scala 2.11

-print

Print program with Scala-specific features removed.

-release RELEASE

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

-sourcepath PATH

Specify location(s) of source files.

-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
-toolcp PATH

Add to the runner classpath.

-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.

@<file>

A text file containing compiler arguments (options and source files)

Advanced Settings

-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: -2147483648
-Xexperimental

Enable experimental extensions.

-Xfatal-warnings

Fail the compilation if there are any warnings.

-Xfull-lubs

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

-Xfuture

Turn on future language features.

-Xgenerate-phase-graph FILE

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

-Xlint:WARNING1,WARNING2

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

-Xlint:adapted-args

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

-Xlint:nullary-unit

Warn when nullary methods return Unit.

-Xlint:inaccessible

Warn about inaccessible types in method signatures.

-Xlint:nullary-override

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

-Xlint:infer-any

Warn when a type argument is inferred to be 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.

-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.

-Xlog-implicit-conversions

Print a message whenever an implicit conversion is inserted.

-Xlog-implicits

Show more detail on why some implicits are not applicable.

-Xlog-reflective-calls

Print a message when a reflective method call is generated

-Xmacro-settings OPTION1,OPTION2

Custom settings for macros.

-Xmain-class PATH

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

-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
-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.

-Xno-forwarders

Do not generate static forwarders in mirror classes.

-Xno-patmat-analysis

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

-Xno-uescape

Disable handling of \u unicode escapes.

-Xnojline

Do not use JLine for editing.

-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: misc/scala-devel/plugins
-Xprint ARG

Print out program after phases

-Xprint-args

Print all compiler arguments and exit.

-Xprint-pos

Print tree positions, as offsets.

-Xprint-types

Print tree types (debugging option).

-Xprompt

Display a prompt after each error (debugging option).

-Xreporter CLASSNAME

Specify a custom reporter for compiler messages.

Default: scala.tools.nsc.reporters.ConsoleReporter
-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.

-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 VERSION

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

Default: 2.12.0
-Xsource-reader CLASSNAME

Specify a custom method for reading source files.

-Xstrict-inference

Don’t infer known-unsound types

-Xverify

Verify generic signatures in generated bytecode.

-Xxml:PROPERTY1,PROPERTY2

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

-Xxml:coalescing

Convert PCData to Text and coalesce sibling nodes

Verbose Settings

Private Settings

-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
-Ybreak-cycles

Attempt to break cycles encountered during typing

-Ybrowse ARG

Browse the abstract syntax tree after phases

-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

-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

-Ycheck ARG

Check the tree at the end of phases

-Ycompact-trees

Use compact tree printer when displaying trees.

-Ydebug

Increase the quantity of debugging output.

-Ydelambdafy:STRATEGY

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

Default: method
-Ydelambdafy:inline
-Ydelambdafy:method
-YdisableFlatCpCaching

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

-Ydoc-debug

Trace all scaladoc activity.

-Ydump-classes DIR

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

-Ygen-asmp DIR

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

-Yhot-statistics-enabled

Enable -Ystatistics to print hot statistics.

-Yide-debug

Generate, validate and output trees using the interactive compiler.

-Yinfer-argument-types

Infer types for arguments of overridden methods.

-Yissue-debug

Print stack traces when a context issues an error.

-Yjar-compression-level ARG

compression level to use when writing jar files

Default: -1
Min: -1
Max: 9
-Ylog ARG

Log operations during phases

-Ylog-classpath

Output information about what classpath is being applied.

-Ymacro-debug-lite

Trace essential macro-related activities.

-Ymacro-debug-verbose

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

-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

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

-Yno-adapted-args

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

-Yno-completion

Disable tab-completion in the REPL.

-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.

-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
-Yopt-log-inline PACKAGE/CLASS.METHOD

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

-Yopt-trace PACKAGE/CLASS.METHOD

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

-Yoverride-objects

Allow member objects to be overridden.

-Yoverride-vars

Allow vars to be overridden.

-Ypartial-unification

Enable partial unification in type constructor inference

-Ypatmat-debug

Trace pattern matching translation.

-Ypatmat-exhaust-depth ARG

off

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

Trace position validation.

-Yprofile-destination FILE

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

-Yprofile-enabled

Enable profiling.

-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
-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: _
-Yquasiquote-debug

Trace quasiquote-related activities.

-Yrangepos

Use range positions for syntax trees.

-Yrecursion ARG

Set recursion depth used when locking symbols.

Default: 0
Min: 0
Max: 2147483647
-Yreify-copypaste

Dump the reified trees in copypasteable representation.

-Yreify-debug

Trace reification.

-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)

-Yrepl-sync

Do not use asynchronous code for repl startup

-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
-Yshow ARG

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

-Yshow-member-pos OUTPUT STYLE

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

-Yshow-symkinds

Print abbreviated symbol kinds next to symbol names.

-Yshow-symowners

Print owner identifiers next to symbol names.

-Yshow-syms

Print the AST symbol hierarchy after each phase.

-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.

-Yskip ARG

Skip phases

-Ystatistics ARG

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

Default: parser,typer,patmat,erasure,cleanup,jvm
-Ystop-after ARG or -stop ARG

Stop after phases

-Ystop-before ARG

Stop before phases

-Ytyper-debug

Trace all type assignments.

-Yvalidate-pos ARG

Validate positions after the given phases (implies -Yrangepos) phases

-Yvirtpatmat

Enable pattern matcher virtualization

-Ywarn-adapted-args

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

-Ywarn-dead-code

Warn when dead code is identified.

-Ywarn-extra-implicit

Warn when more than one implicit parameter section is defined.

-Ywarn-inaccessible

Warn about inaccessible types in method signatures.

-Ywarn-infer-any

Warn when a type argument is inferred to be Any.

-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-nullary-override

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

-Ywarn-nullary-unit

Warn when nullary methods return Unit.

-Ywarn-numeric-widen

Warn when numerics are widened.

-Ywarn-self-implicit

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

-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-unused-import

Warn when imports are unused.

-Ywarn-value-discard

Warn when non-Unit expression results are unused.

Warning Settings

-Xlint:WARNING1,WARNING2

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

-Xlint:adapted-args

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

-Xlint:nullary-unit

Warn when nullary methods return Unit.

-Xlint:inaccessible

Warn about inaccessible types in method signatures.

-Xlint:nullary-override

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

-Xlint:infer-any

Warn when a type argument is inferred to be 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-any-thread

Allow use of the presentation compiler from any thread

-Ypresentation-debug

Enable debugging output for the presentation compiler.

-Ypresentation-delay ARG

Wait number of ms after typing before starting typechecking

Default: 0
Min: 0
Max: 999
-Ypresentation-log FILE

Log presentation compiler events into file

-Ypresentation-replay FILE

Replay presentation compiler events from file

-Ypresentation-strict

Do not report type errors in sources with syntax errors.

-Ypresentation-verbose

Print information about presentation compiler tasks.

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: