0
# Annotations
1
2
Comprehensive annotation system including experimental features, macro annotations, and compiler hints supporting both behavioral annotations and metaprogramming constructs.
3
4
## Capabilities
5
6
### Core Annotations
7
8
Essential annotations for marking definitions and controlling compiler behavior.
9
10
```scala { .api }
11
/**
12
* Mark definitions as experimental
13
* Requires -Xsource-features flag or explicit import to use
14
*/
15
final class experimental extends StaticAnnotation
16
17
/**
18
* Define external names for definitions
19
* Useful for interoperability and avoiding naming conflicts
20
*/
21
final class targetName(name: String) extends StaticAnnotation
22
23
/**
24
* Mark fields as static (platform-specific behavior)
25
* Generates static fields on JVM, affects JS/Native compilation
26
*/
27
final class static extends StaticAnnotation
28
```
29
30
**Usage Examples:**
31
32
```scala
33
import scala.annotation.experimental
34
35
// Experimental API
36
@experimental
37
def newFeature(): String = "This is experimental"
38
39
// External naming
40
class MathUtils:
41
@targetName("add")
42
def +(x: Int, y: Int): Int = x + y
43
44
@targetName("multiply")
45
def *(x: Int, y: Int): Int = x * y
46
47
// Static field
48
class Constants:
49
@static val PI = 3.14159
50
@static val E = 2.71828
51
52
// Usage requires experimental import
53
import scala.annotation.experimental.given
54
val result = newFeature() // Now allowed
55
56
// External names are used in bytecode/JS output
57
val math = MathUtils()
58
val sum = math.+(5, 3) // Compiled as "add"
59
```
60
61
### Macro System Annotations
62
63
Annotations for macro and metaprogramming support.
64
65
```scala { .api }
66
/**
67
* Base trait for macro annotation implementations
68
* Experimental feature for compile-time code transformation
69
*/
70
trait MacroAnnotation extends StaticAnnotation:
71
/** Transform definition and optional companion */
72
def transform(definition: Any, companion: Option[Any]): List[Any]
73
74
/**
75
* Base trait for annotations that refine types
76
* Used for type-level transformations and refinements
77
*/
78
trait RefiningAnnotation extends StaticAnnotation
79
```
80
81
**Usage Examples:**
82
83
```scala
84
import scala.annotation.MacroAnnotation
85
86
// Custom macro annotation
87
class toString extends MacroAnnotation:
88
def transform(definition: Any, companion: Option[Any]): List[Any] =
89
// Generate toString method for case classes
90
// Implementation details handled by compiler
91
List(definition) // Simplified
92
93
// Usage of macro annotation
94
@toString
95
case class Person(name: String, age: Int)
96
// Automatically generates custom toString method
97
98
// Refining annotation example
99
class refined[P] extends RefiningAnnotation
100
101
type PositiveInt = Int @refined[Positive]
102
103
def processPositive(n: PositiveInt): String = s"Processing $n"
104
105
// Type refinement (conceptual - actual implementation more complex)
106
val positive: PositiveInt = 42.asInstanceOf[PositiveInt]
107
```
108
109
### Behavioral Annotations
110
111
Annotations that modify compilation behavior and provide compiler hints.
112
113
```scala { .api }
114
/**
115
* Enable alpha renaming for bindings
116
* Allows same name to be used in nested scopes
117
*/
118
class alpha extends StaticAnnotation
119
120
/**
121
* Mark types as capabilities in the capability system
122
*/
123
class capability extends StaticAnnotation
124
125
/**
126
* Restrict annotation to constructor use only
127
*/
128
class constructorOnly extends StaticAnnotation
129
130
/**
131
* Mark parameters as initialization parameters
132
* Used in capability system for tracking initialization
133
*/
134
class init extends StaticAnnotation
135
136
/**
137
* Transform type A into B (contextual abstraction)
138
*/
139
class into[B] extends StaticAnnotation
140
141
/**
142
* Make private members visible in binary (for internal use)
143
*/
144
class publicInBinary extends StaticAnnotation
145
146
/**
147
* Indicate that a method retains/captures its parameters
148
*/
149
class retains extends StaticAnnotation
150
151
/**
152
* Indicate method retains by-name parameters
153
*/
154
class retainsByName extends StaticAnnotation
155
156
/**
157
* Mark code as thread-unsafe (optimization hint)
158
*/
159
class threadUnsafe extends StaticAnnotation
160
161
/**
162
* Mark traits as transparent (no virtual dispatch overhead)
163
*/
164
class transparentTrait extends StaticAnnotation
165
166
/**
167
* Hint compiler to unroll loops/recursion
168
*/
169
class unroll extends StaticAnnotation
170
```
171
172
**Usage Examples:**
173
174
```scala
175
// Alpha renaming
176
def nested(): Unit =
177
val x = 1
178
@alpha def inner() =
179
val x = 2 // Allowed due to alpha annotation
180
x
181
182
// Capability annotation
183
@capability
184
trait FileSystem
185
186
// Constructor-only annotation
187
@constructorOnly
188
class InitOnly(value: String)
189
190
// Initialization parameter
191
class Service(@init connection: DatabaseConnection)
192
193
// Type transformation
194
type UserId = Int @into[String]
195
196
// Thread safety hint
197
@threadUnsafe
198
class FastCounter:
199
private var count = 0
200
def increment(): Unit = count += 1
201
202
// Transparent trait for performance
203
@transparentTrait
204
trait Additive[T]:
205
def add(x: T, y: T): T
206
207
// Loop unrolling hint
208
@unroll
209
def factorial(n: Int): Int =
210
if n <= 1 then 1 else n * factorial(n - 1)
211
```
212
213
### Internal Compiler Annotations
214
215
Annotations used internally by the Scala compiler (typically not used in user code).
216
217
```scala { .api }
218
// Internal annotations (simplified subset)
219
class Alias(aliasee: String) extends StaticAnnotation
220
class AnnotationDefault() extends StaticAnnotation
221
class AssignedNonLocally() extends StaticAnnotation
222
class Body() extends StaticAnnotation
223
class CaptureChecked() extends StaticAnnotation
224
class Child() extends StaticAnnotation
225
class ContextResultCount(count: Int) extends StaticAnnotation
226
class ErasedParam() extends StaticAnnotation
227
class InlineParam() extends StaticAnnotation
228
class MappedAlternative() extends StaticAnnotation
229
class ProvisionalSuperClass() extends StaticAnnotation
230
class Repeated() extends StaticAnnotation
231
class RuntimeChecked() extends StaticAnnotation
232
class SourceFile(path: String) extends StaticAnnotation
233
class WithPureFuns() extends StaticAnnotation
234
class WitnessNames() extends StaticAnnotation
235
```
236
237
**Usage Examples:**
238
239
```scala
240
// These are typically generated by the compiler, not written by users
241
242
// Alias annotation (compiler-generated)
243
@Alias("originalName")
244
type TypeAlias = String
245
246
// Erased parameter tracking
247
def generic[T](@ErasedParam evidence: ClassTag[T]): Array[T] =
248
new Array[T](0)
249
250
// Inline parameter tracking
251
inline def inlineMethod(@InlineParam x: Int): Int = x + 1
252
```
253
254
### Preview and Development Annotations
255
256
Annotations for preview features and development aids.
257
258
```scala { .api }
259
/**
260
* Mark definitions as preview features
261
* Subject to change in future versions
262
*/
263
class preview extends StaticAnnotation
264
265
/**
266
* Express reachability of capabilities (internal)
267
*/
268
class reachCapability extends StaticAnnotation
269
270
/**
271
* Require specific capabilities for usage
272
*/
273
class requiresCapability extends StaticAnnotation
274
275
/**
276
* Mark data as sharable between capability domains
277
*/
278
class sharable extends StaticAnnotation
279
280
/**
281
* Mark data as unshared (capability isolation)
282
*/
283
class unshared extends StaticAnnotation
284
```
285
286
**Usage Examples:**
287
288
```scala
289
// Preview feature
290
@preview
291
def experimentalAPI(): Future[String] =
292
Future.successful("This API may change")
293
294
// Capability requirements
295
@requiresCapability
296
def secureOperation()(using Security): Unit =
297
// Requires Security capability
298
299
// Sharable data
300
@sharable
301
case class ImmutableData(value: String)
302
303
// Unshared data
304
@unshared
305
class MutableResource(var state: Int)
306
```
307
308
### Unchecked Annotations
309
310
Annotations for suppressing capability and safety checks.
311
312
```scala { .api }
313
/**
314
* Suppress capability leak warnings
315
* Use when you know capability leaks are safe
316
*/
317
class uncheckedCapabilityLeaks extends StaticAnnotation
318
319
/**
320
* Suppress capture checking warnings
321
* Use when you know captures are handled correctly
322
*/
323
class uncheckedCaptures extends StaticAnnotation
324
```
325
326
**Usage Examples:**
327
328
```scala
329
import scala.annotation.unchecked.*
330
331
// Suppress capability leak warnings
332
@uncheckedCapabilityLeaks
333
def leakyFunction(resource: FileHandle): () => String =
334
() => resource.read() // Normally would warn about capability leak
335
336
// Suppress capture warnings
337
@uncheckedCaptures
338
def complexCapturing[C](f: () => C): C =
339
// Complex capability management that compiler can't verify
340
f()
341
```
342
343
### Standard Library Annotations
344
345
Common annotations from the standard annotation package.
346
347
```scala { .api }
348
// Re-exported from scala.annotation for convenience
349
class deprecated(message: String = "", since: String = "") extends StaticAnnotation
350
class throws[T <: Throwable] extends StaticAnnotation
351
class tailrec extends StaticAnnotation
352
class inline extends StaticAnnotation
353
class native extends StaticAnnotation
354
class strictfp extends StaticAnnotation
355
class volatile extends StaticAnnotation
356
class transient extends StaticAnnotation
357
```
358
359
**Usage Examples:**
360
361
```scala
362
// Deprecation
363
@deprecated("Use newMethod instead", since = "1.2.0")
364
def oldMethod(): String = "deprecated"
365
366
// Exception documentation
367
@throws[IllegalArgumentException]
368
def validateInput(input: String): String =
369
if input.isEmpty then throw IllegalArgumentException("Empty input")
370
else input
371
372
// Tail recursion optimization
373
@tailrec
374
def factorial(n: Int, acc: Int = 1): Int =
375
if n <= 1 then acc else factorial(n - 1, n * acc)
376
377
// Inline expansion
378
@inline
379
def fastComputation(x: Int): Int = x * x + 1
380
381
// Platform-specific annotations
382
@native
383
def platformSpecific(): Unit
384
385
@volatile
386
var sharedCounter: Int = 0
387
388
@transient
389
val temporaryData: List[String] = List()
390
```
391
392
## Types
393
394
```scala { .api }
395
// Core annotation types
396
final class experimental extends StaticAnnotation
397
final class targetName(name: String) extends StaticAnnotation
398
final class static extends StaticAnnotation
399
400
// Macro system
401
trait MacroAnnotation extends StaticAnnotation:
402
def transform(definition: Any, companion: Option[Any]): List[Any]
403
trait RefiningAnnotation extends StaticAnnotation
404
405
// Behavioral annotations
406
class alpha extends StaticAnnotation
407
class capability extends StaticAnnotation
408
class constructorOnly extends StaticAnnotation
409
class init extends StaticAnnotation
410
class into[B] extends StaticAnnotation
411
class publicInBinary extends StaticAnnotation
412
class retains extends StaticAnnotation
413
class retainsByName extends StaticAnnotation
414
class threadUnsafe extends StaticAnnotation
415
class transparentTrait extends StaticAnnotation
416
class unroll extends StaticAnnotation
417
418
// Preview and capability annotations
419
class preview extends StaticAnnotation
420
class reachCapability extends StaticAnnotation
421
class requiresCapability extends StaticAnnotation
422
class sharable extends StaticAnnotation
423
class unshared extends StaticAnnotation
424
425
// Unchecked annotations
426
class uncheckedCapabilityLeaks extends StaticAnnotation
427
class uncheckedCaptures extends StaticAnnotation
428
429
// Internal compiler annotations (subset)
430
class Alias(aliasee: String) extends StaticAnnotation
431
class ErasedParam() extends StaticAnnotation
432
class InlineParam() extends StaticAnnotation
433
class SourceFile(path: String) extends StaticAnnotation
434
```