Implicit conversions are defined by given
instances of the scala.Conversion class.
For example, not accounting for possible conversion errors, this code defines an an implicit conversion from String
to Int
:
given Conversion[String, Int] with
def apply(s: String): Int = Integer.parseInt(s)
Using an alias this can be expressed more concisely as:
given Conversion[String, Int] = Integer.parseInt(_)
Using either of those conversions, you can now use a String
in places where an Int
is expected:
import scala.language.implicitConversions
// a method that expects an Int
def plus1(i: Int) = i + 1
// pass it a String that converts to an Int
plus1("1")
Discussion
The Predef package contains “auto-boxing” conversions that map primitive number types to subclasses of java.lang.Number.
For instance, the conversion from Int
to java.lang.Integer can be defined as follows:
given int2Integer: Conversion[Int, java.lang.Integer] =
java.lang.Integer.valueOf(_)
Contributors to this page:
Contents
- Introduction
- Scala 3 Features
- Why Scala 3?
- A Taste of Scala
- Hello, World!
- The REPL
- Variables and Data Types
- Control Structures
- Domain Modeling
- Methods
- First-Class Functions
- Objects
- Collections
- Contextual Abstractions
- Toplevel Definitions
- Summary
- A First Look at Types
- Control Structures
- Domain Modeling
- Tools
- OOP Modeling
- FP Modeling
- Methods
- Method Features
- main Methods
- Summary
- Functions
- Anonymous Functions
- Function Variables
- Eta Expansion
- Higher-Order Functions
- Write Your Own map Method
- Creating a Method That Returns a Function
- Summary
- Packaging and Imports
- Scala Collections
- Collections Types
- Collections Methods
- Summary
- Functional Programming
- What is Functional Programming?
- Immutable Values
- Pure Functions
- Functions Are Values
- Functional Error Handling
- Summary
- Types and the Type System
- Inferred Types
- Generics
- Intersection Types
- Union Types
- Algebraic Data Types
- Variance
- Opaque Types
- Structural Types
- Dependent Function Types
- Other Types
- Contextual Abstractions
- Given Instances and Using Clauses
- Type Classes
- Context Bounds
- Given Imports
- Extension Methods
- Implementing Type Classes
- Multiversal Equality
- Implicit Conversions
- Summary
- Concurrency
- Scala Tools
- Interacting with Java
- Scala for Java Developers
- Scala for JavaScript Developers
- Scala for Python Developers