> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Kotlin Object Expression

An object expression in Kotlin is an expression that instantiates an anonymous class at runtime. Unlike object declarations, which define lazy singletons, an object expression evaluates immediately upon execution and generates a distinct, non-singleton instance each time it is evaluated.

## Syntax

The `object` keyword is used to define the anonymous class. It can inherit from classes, implement interfaces, or be declared without any supertypes.

**Without a Supertype:**

```kotlin theme={"dark"}
val anonymousObject = object {
    val property: String = "Value"
    fun method() = "Action"
}
```

**Inheriting from a Class and Implementing Interfaces:**
If the anonymous class requires a supertype, the type is specified after a colon. Constructor parameters for the superclass must be passed directly. If an anonymous object has multiple supertypes and is exposed as a non-private declaration, the Kotlin compiler requires an explicit type declaration to resolve which supertype is exposed.

```kotlin theme={"dark"}
open class BaseClass(val id: Int)
interface BaseInterface

// Explicit type declaration is required here
val complexObject: BaseClass = object : BaseClass(42), BaseInterface {
    override fun toString(): String {
        return "Anonymous instance with id: $id"
    }
}
```

## Lexical Scope and Closures

Object expressions can access and mutate variables from their enclosing lexical scope. Unlike Java, Kotlin does not require captured variables to be `final` or effectively final.

```kotlin theme={"dark"}
fun executeWithState() {
    var executionCount = 0
    
    val statefulObject = object {
        fun track() {
            executionCount++ // Mutating the captured variable directly
        }
    }
    
    statefulObject.track()
}
```

## Type System Implications

The Kotlin compiler handles the type of an anonymous object differently depending on its visibility and scope.

**Local and Private Scope:**
When an object expression is assigned to a local variable or a `private` property/function, the compiler retains the anonymous type. Any custom properties or functions defined exclusively inside the object remain accessible.

```kotlin theme={"dark"}
class Container {
    // Private visibility retains the anonymous type
    private val privateObj = object {
        val customProperty = "Accessible"
    }

    fun access() {
        println(privateObj.customProperty) // Valid compilation
    }
}
```

**Public, Protected, and Internal Scope:**
When an object expression is returned from a `public`, `protected`, or `internal` function, or assigned to a property with one of these visibilities, the compiler degrades the type to the explicitly declared supertype. If no supertype is declared, the type resolves to `Any`. Members specific to the anonymous object become inaccessible to the outside scope.

```kotlin theme={"dark"}
class PublicContainer {
    // Public visibility degrades type to 'Any'
    val publicObj = object {
        val customProperty = "Inaccessible"
    }

    // Internal visibility degrades type to 'BaseInterface'
    internal val typedObj = object : BaseInterface {
        val customProperty = "Inaccessible"
    }

    fun access() {
        // publicObj.customProperty // Compilation error: Unresolved reference
        // typedObj.customProperty  // Compilation error: Unresolved reference
    }
}
```

## Memory and Compilation

At the bytecode level, the Kotlin compiler generates a standard JVM anonymous inner class (e.g., `EnclosingClass$1.class`) for each object expression. Because a new instance is allocated on the heap every time the expression is evaluated, placing object expressions inside loops or frequently called functions incurs standard object allocation overhead.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Kotlin Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
