🎓 A1Learner
🔍
0 of 45 lessons completed

Transparent Inline

Transparent inline is an inline method whose result type is more precise than its declared type. The precise type lets later code use the result in a direct way.

The true branch keeps an Int result

The method picks 10 for true. The result is stored as an Int and five is added.

transparent inline def pick(inline b: Boolean) = if b then 10 else "ten"
@main def main(): Unit =
  val n: Int = pick(true)
  println(n + 5)

The false branch keeps a String result

The method picks ten for false. The result is stored as a String and its length is printed.

transparent inline def pick(inline b: Boolean) = if b then 10 else "ten"
@main def main(): Unit =
  val s: String = pick(false)
  println(s.length)

Both branches keep their own types in one program

One call stores an Int result. The other call stores a String result.

transparent inline def pick(inline b: Boolean) = if b then 10 else "ten"
@main def main(): Unit =
  val n: Int = pick(true)
  val s: String = pick(false)
  println(n)
  println(s.length)

Example

transparent inline def pick(inline b: Boolean) = if b then 10 else "ten"
@main def main(): Unit =
  val score: Int = pick(true)
  val word: String = pick(false)
  println(score)
  println(word.length)
  println(score + word.length)

Key points

  • Transparent inline: A transparent inline method is an inline method whose result type follows the chosen branch.
  • Branch: A branch is one path inside an if expression.
  • Result type: A result type is the type of value a method returns.
  • Precise type: A precise type is the exact type of one branch result, not a shared general type.
  • Use a transparent inline method to keep the exact type of a chosen value.

In this example, the method picks 10 for true and ten for false. The main program stores the first result as an Int and the second result as a String. It then prints the score, the word length, and their sum.

Note

Scala requires the word transparent before inline for this precise result type.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does a transparent inline method keep that a plain inline method does not?