<commit_before>[[kotlin]]
= Kotlin

https://kotlinlang.org[Kotlin] is a statically-typed language targeting the JVM (and other platforms)
which allows writing concise and elegant code while providing very good
https://kotlinlang.org/docs/reference/java-interop.html[interoperability] with
existing libraries written in Java.

The Spring Framework provides first-class support for Kotlin that allows developers to write
Kotlin applications almost as if the Spring Framework was a native Kotlin framework.




[[kotlin-requirements]]
== Requirements

Spring Framework supports Kotlin 1.1+ and requires
https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-stdlib[`kotlin-stdlib`]
(or one of its https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-stdlib-jre7[`kotlin-stdlib-jre7`]
/ https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-stdlib-jre8[`kotlin-stdlib-jre8`] variants)
and https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-reflect[`kotlin-reflect`]
to be present on the classpath. They are provided by default if one bootstraps a Kotlin project on
https://start.spring.io/#!language=kotlin[start.spring.io].




[[kotlin-extensions]]
== Extensions

Kotlin https://kotlinlang.org/docs/reference/extensions.html[extensions] provide the ability
to extend existing classes with additional functionality. The Spring Framework Kotlin APIs make
use of these extensions to add new Kotlin specific conveniences to existing Spring APIs.

{doc-root}/spring-framework/docs/{spring-version}/kdoc-api/spring-framework/[Spring Framework KDoc API] lists
and documents all the Kotlin extensions and DSLs available.

[NOTE]
====
Keep in mind that Kotlin extensions need to be imported to be used. This means
for example that the `GenericApplicationContext.registerBean` Kotlin extension
will only be available if `import org.springframework.context.support.registerBean` is imported.
That said, similar to static imports, an IDE should automatically suggest the import in most cases.
====

For example, https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters[Kotlin reified type parameters]
provide a workaround for JVM https://docs.oracle.com/javase/tutorial/java/generics/erasure.html[generics type erasure],
and Spring Framework provides some extensions to take advantage of this feature.
This allows for a better Kotlin API `RestTemplate`, the new `WebClient` from Spring
WebFlux and for various other APIs.

[NOTE]
====
Other libraries like Reactor and Spring Data also provide Kotlin extensions
for their APIs, thus giving a better Kotlin development experience overall.
====

To retrieve a list of `Foo` objects in Java, one would normally write:

[source,java,indent=0]
----
	Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)
----

Whilst with Kotlin and Spring Framework extensions, one is able to write:

[source,kotlin,indent=0]
----
	val users = client.get().retrieve().bodyToFlux<User>()
	// or (both are equivalent)
	val users : Flux<User> = client.get().retrieve().bodyToFlux()
----

As in Java, `users` in Kotlin is strongly typed, but Kotlin's clever type inference allows
for shorter syntax.




[[kotlin-null-safety]]
== Null-safety

One of Kotlin's key features is https://kotlinlang.org/docs/reference/null-safety.html[null-safety]
- which cleanly deals with `null` values at compile time rather than bumping into the famous
`NullPointerException` at runtime. This makes applications safer through nullability
declarations and expressing "value or no value" semantics without paying the cost of wrappers like `Optional`.
(Kotlin allows using functional constructs with nullable values; check out this
http://www.baeldung.com/kotlin-null-safety[comprehensive guide to Kotlin null-safety].)

Although Java does not allow one to express null-safety in its type-system, Spring Framework now
provides <<core#null-safety,null-safety of the whole Spring Framework API>>
via tooling-friendly annotations declared in the `org.springframework.lang` package.
By default, types from Java APIs used in Kotlin are recognized as
https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types[platform types]
for which null-checks are relaxed.
https://github.com/Kotlin/KEEP/blob/jsr-305/proposals/jsr-305-custom-nullability-qualifiers.md[Kotlin support for JSR 305 annotations]
+ Spring nullability annotations provide null-safety for the whole Spring Framework API to Kotlin developers,
with the advantage of dealing with `null` related issues at compile time.

[NOTE]
====
Libraries like Reactor or Spring Data provide null-safe APIs leveraging this feature.
====

The JSR 305 checks can be configured by adding the `-Xjsr305` compiler flag with the following
options: `-Xjsr305={strict|warn|ignore}`.

For kotlin versions 1.1.50+, the default behavior is the same to `-Xjsr305=warn`.
The `strict` value is required to have Spring Framework API full null-safety taken in account
but should be considered experimental since Spring API nullability declaration could evolve
even between minor releases and more checks may be added in the future).

[NOTE]
====
Generic type arguments, varargs and array elements nullability are not supported yet,
but should be in an upcoming release, see https://github.com/Kotlin/KEEP/issues/79[this dicussion]
for up-to-date information.
====




[[kotlin-classes-interfaces]]
== Classes & Interfaces

Spring Framework supports various Kotlin constructs like instantiating Kotlin classes
via primary constructors, immutable classes data binding and function optional parameters
with default values.

Kotlin parameter names are recognized via a dedicated `KotlinReflectionParameterNameDiscoverer`
which allows finding interface method parameter names without requiring the Java 8 `-parameters`
compiler flag enabled during compilation.

https://github.com/FasterXML/jackson-module-kotlin[Jackson Kotlin module] which is required
for serializing / deserializing JSON data is automatically registered when
found in the classpath and a warning message will be logged if Jackson and Kotlin are
detected without the Jackson Kotlin module present.




[[kotlin-annotations]]
== Annotations

Spring Framework also takes advantage of https://kotlinlang.org/docs/reference/null-safety.html[Kotlin null-safety]
to determine if a HTTP parameter is required without having to explicitly
define the `required` attribute.  That means `@RequestParam name: String?` will be treated
as not required and conversely `@RequestParam name: String` as being required.
This feature is also supported on the Spring Messaging `@Header` annotation.

In a similar fashion, Spring bean injection with `@Autowired` or `@Inject` uses this information
to determine if a bean is required or not. `@Autowired lateinit var foo: Foo` implies that a bean
of type `Foo` must be registered in the application context while `@Autowired lateinit var foo: Foo?`
won’t raise an error if such bean does not exist.

[NOTE]
====<commit_msg>Document @Bean nullable parameters optional bean injection<commit_after>[[kotlin]]
= Kotlin

https://kotlinlang.org[Kotlin] is a statically-typed language targeting the JVM (and other platforms)
which allows writing concise and elegant code while providing very good
https://kotlinlang.org/docs/reference/java-interop.html[interoperability] with
existing libraries written in Java.

The Spring Framework provides first-class support for Kotlin that allows developers to write
Kotlin applications almost as if the Spring Framework was a native Kotlin framework.




[[kotlin-requirements]]
== Requirements

Spring Framework supports Kotlin 1.1+ and requires
https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-stdlib[`kotlin-stdlib`]
(or one of its https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-stdlib-jre7[`kotlin-stdlib-jre7`]
/ https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-stdlib-jre8[`kotlin-stdlib-jre8`] variants)
and https://bintray.com/bintray/jcenter/org.jetbrains.kotlin%3Akotlin-reflect[`kotlin-reflect`]
to be present on the classpath. They are provided by default if one bootstraps a Kotlin project on
https://start.spring.io/#!language=kotlin[start.spring.io].




[[kotlin-extensions]]
== Extensions

Kotlin https://kotlinlang.org/docs/reference/extensions.html[extensions] provide the ability
to extend existing classes with additional functionality. The Spring Framework Kotlin APIs make
use of these extensions to add new Kotlin specific conveniences to existing Spring APIs.

{doc-root}/spring-framework/docs/{spring-version}/kdoc-api/spring-framework/[Spring Framework KDoc API] lists
and documents all the Kotlin extensions and DSLs available.

[NOTE]
====
Keep in mind that Kotlin extensions need to be imported to be used. This means
for example that the `GenericApplicationContext.registerBean` Kotlin extension
will only be available if `import org.springframework.context.support.registerBean` is imported.
That said, similar to static imports, an IDE should automatically suggest the import in most cases.
====

For example, https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters[Kotlin reified type parameters]
provide a workaround for JVM https://docs.oracle.com/javase/tutorial/java/generics/erasure.html[generics type erasure],
and Spring Framework provides some extensions to take advantage of this feature.
This allows for a better Kotlin API `RestTemplate`, the new `WebClient` from Spring
WebFlux and for various other APIs.

[NOTE]
====
Other libraries like Reactor and Spring Data also provide Kotlin extensions
for their APIs, thus giving a better Kotlin development experience overall.
====

To retrieve a list of `Foo` objects in Java, one would normally write:

[source,java,indent=0]
----
	Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)
----

Whilst with Kotlin and Spring Framework extensions, one is able to write:

[source,kotlin,indent=0]
----
	val users = client.get().retrieve().bodyToFlux<User>()
	// or (both are equivalent)
	val users : Flux<User> = client.get().retrieve().bodyToFlux()
----

As in Java, `users` in Kotlin is strongly typed, but Kotlin's clever type inference allows
for shorter syntax.




[[kotlin-null-safety]]
== Null-safety

One of Kotlin's key features is https://kotlinlang.org/docs/reference/null-safety.html[null-safety]
- which cleanly deals with `null` values at compile time rather than bumping into the famous
`NullPointerException` at runtime. This makes applications safer through nullability
declarations and expressing "value or no value" semantics without paying the cost of wrappers like `Optional`.
(Kotlin allows using functional constructs with nullable values; check out this
http://www.baeldung.com/kotlin-null-safety[comprehensive guide to Kotlin null-safety].)

Although Java does not allow one to express null-safety in its type-system, Spring Framework now
provides <<core#null-safety,null-safety of the whole Spring Framework API>>
via tooling-friendly annotations declared in the `org.springframework.lang` package.
By default, types from Java APIs used in Kotlin are recognized as
https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types[platform types]
for which null-checks are relaxed.
https://github.com/Kotlin/KEEP/blob/jsr-305/proposals/jsr-305-custom-nullability-qualifiers.md[Kotlin support for JSR 305 annotations]
+ Spring nullability annotations provide null-safety for the whole Spring Framework API to Kotlin developers,
with the advantage of dealing with `null` related issues at compile time.

[NOTE]
====
Libraries like Reactor or Spring Data provide null-safe APIs leveraging this feature.
====

The JSR 305 checks can be configured by adding the `-Xjsr305` compiler flag with the following
options: `-Xjsr305={strict|warn|ignore}`.

For kotlin versions 1.1.50+, the default behavior is the same to `-Xjsr305=warn`.
The `strict` value is required to have Spring Framework API full null-safety taken in account
but should be considered experimental since Spring API nullability declaration could evolve
even between minor releases and more checks may be added in the future).

[NOTE]
====
Generic type arguments, varargs and array elements nullability are not supported yet,
but should be in an upcoming release, see https://github.com/Kotlin/KEEP/issues/79[this dicussion]
for up-to-date information.
====




[[kotlin-classes-interfaces]]
== Classes & Interfaces

Spring Framework supports various Kotlin constructs like instantiating Kotlin classes
via primary constructors, immutable classes data binding and function optional parameters
with default values.

Kotlin parameter names are recognized via a dedicated `KotlinReflectionParameterNameDiscoverer`
which allows finding interface method parameter names without requiring the Java 8 `-parameters`
compiler flag enabled during compilation.

https://github.com/FasterXML/jackson-module-kotlin[Jackson Kotlin module] which is required
for serializing / deserializing JSON data is automatically registered when
found in the classpath and a warning message will be logged if Jackson and Kotlin are
detected without the Jackson Kotlin module present.




[[kotlin-annotations]]
== Annotations

Spring Framework also takes advantage of https://kotlinlang.org/docs/reference/null-safety.html[Kotlin null-safety]
to determine if a HTTP parameter is required without having to explicitly
define the `required` attribute.  That means `@RequestParam name: String?` will be treated
as not required and conversely `@RequestParam name: String` as being required.
This feature is also supported on the Spring Messaging `@Header` annotation.

In a similar fashion, Spring bean injection with `@Autowired`, `@Bean` or `@Inject` uses
this information to determine if a bean is required or not.

For example, `@Autowired lateinit var foo: Foo` implies that a bean
of type `Foo` must be registered in the application context, while `@Autowired lateinit var foo: Foo?`
won’t raise an error if such bean does not exist.

Following the same principle, `@Bean fun baz(foo: Foo, bar: Bar?) = Baz(foo, bar)` implies
that a bean of type `Foo` must be registered in the application context while a bean of
type `Bar` may or may not exist. The same behavior applies to autowired constructor parameters.

[NOTE]
====
{'fraction_non_alphanumeric': 0.08219652378644138, 'fraction_numerical': 0.0055397825635343815, 'mean_word_length': 5.246539792387543, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 32, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6874374', 'n_tokens_mistral': 4154, 'n_tokens_neox': 3862, 'n_words': 1616}