A type cast operator changes the static type of an expression after performing a run-time check.

h3. Smart casts

In many cases, one does not need to use explicit cast operators in [Kotlin], because the compiler tracks the [*is*\-checks for immutable values|Pattern matching] and inserts (safe) casts automatically when needed:
{jet}
fun demo(x : Any) {
  if (x is String) {
    print(x.length) // x is automatically cast to String
  }
}
{jet}

Automatic casts work for [*when* expressions|Control structures#When] and [*while*|Control structures#While] loops as well:
{jet}
when (x) {
  is Int -> print(x + 1)
  is String -> print(x.length + 1)
  is Array<Int> -> print(x.sum())
}
{jet}

h3. "Unsafe" cast operator

Usually, cast operator throws an exception if the cast is not possible. Thus, we call it _unsafe_. The unsafe cast in [Kotlin] is done by an infix operator *as* (see [operator precedence|Grammar#Precedence]):
{jet}
val x : String = y as String
{jet}
Note that *null* cannot be cast to {{String}} as this type is not [nullable|Null-safety], i.e. if {{y}} is *null*, the code above throws an exception.
In order to match Java cast semantics we have to have nullable type at cast right hand side, like
{jet}
val x : String? = y as String?
{jet}

h3. "Safe" (nullable) cast operator

To avoid an exception being thrown, one can use a "safe" cast operator *as?* that returns *null* on failure:
{jet}
val x : String? = y as? String
{jet}
Note that despite the fact that the right-hand side of *as?* is a non-null type {{String}} the result of the cast is nullable.

h3. What's next

* [Pattern matching]