Вывод типов
Позвольте компилятору определить типы.
«Вывод типов» — бесплатный урок Scala for Backend Engineering & Functional Programming на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Scala for Backend Engineering & Functional Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What Is Type Inference?
Scala is statically typed, yet you rarely have to write types out. The compiler infers them from the value on the right-hand side.
This gives you the safety of types with the brevity of a dynamic language.
val n = 42 // inferred Int
val label = "hi" // inferred StringInferring From Literals
When you write val x = 5, the compiler sees the Int literal and gives x the type Int.
A decimal literal becomes a Double, and quoted text becomes a String.
object Main extends App {
val count = 5
val ratio = 1.5
println(count + ratio)
}Inference for Function Returns
The compiler can also infer a method's return type from its body.
Here square returns an Int because the body multiplies two Int values. You did not have to state it.
object Main extends App {
def square(x: Int) = x * x
println(square(6))
}Parameters Still Need Types
Inference has limits. Method parameters must be annotated, because the compiler has nothing to infer them from.
The snippet below would not compile without the : Int on x.
def increment(x: Int) = x + 1 // type on x is requiredInferred Common Type
When values could be several types, Scala infers the most specific common type.
Mixing an Int and a Double in arithmetic widens the result to Double.
object Main extends App {
val mixed = 3 + 2.0 // Double
println(mixed)
}Inference in Collections
Collections infer their element type from the values you put in.
A list of integers becomes List[Int] automatically, so you keep full type safety without annotations.
object Main extends App {
val nums = List(1, 2, 3) // List[Int]
println(nums.sum)
}When Inference Surprises You
Sometimes inference picks a wider type than you want. A list of mixed numbers may infer List[Double] or even List[AnyVal].
If the inferred type is wrong for your needs, add an explicit annotation.
val a = List(1, 2.0) // List[Double]
val b = List(1, "two") // List[Any]Override With Annotations
You can always be explicit. Annotating a type both documents your intent and overrides a too-narrow inference.
Here the literal 7 is widened to a Long on purpose.
val seconds: Long = 7
val data: List[Int] = List(1, 2, 3)Public APIs: Be Explicit
A common style rule: let inference handle local vals, but write explicit return types on public methods.
This keeps your library's contract stable even if the implementation changes.
def total(items: List[Int]): Int = items.sumInference Keeps Type Safety
Inference does not weaken the type system. The compiler still rejects invalid operations.
Below, name is inferred as String, so multiplying it by a number fails to compile, exactly as it should.
val name = "Lia"
val bad = name * 3 // error: value * is not a member of String in this senseInferred val Is Still Immutable
Inference only fills in the type. It does not change whether a binding is mutable.
A val n = 10 is still immutable and fixed as an Int; the compiler simply saved you from typing : Int.
object Main extends App {
val n = 10 // inferred Int, still a val
println(n * n)
}Quick Check
Where does Scala still require you to write a type?
Recap
Type inference lets Scala stay concise without losing static safety.
- Local
vals and return types are usually inferred. - Method parameters must be annotated.
- Inference picks the most specific common type.
- Annotate explicitly for public APIs or to override surprising inference.
Часто задаваемые вопросы
Урок «Вывод типов» бесплатный?
Да — полный текст урока «Вывод типов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Scala for Backend Engineering & Functional Programming, подпишись на CoddyKit PRO. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.
Чему я научусь в уроке «Вывод типов»?
Позвольте компилятору определить типы. Ты практикуешь Scala for Backend Engineering & Functional Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Scala for Backend Engineering & Functional Programming?
Предыдущий опыт не требуется. Scala for Backend Engineering & Functional Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Вывод типов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Scala for Backend Engineering & Functional Programming?
Да. Каждый урок Scala for Backend Engineering & Functional Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.