Skip to content

Default parameter values can't access class scope? #35121

Open
@spyro2000

Description

@spyro2000

I have a spring service with some injected values. But all injected values are nullwhen accessing them from a default parameter value.

Steps to reproduce

  1. Write a simple spring component (service)
  2. Set a default for an optional parameter and reference an injected (non-nullable) member property
  3. Call this method

Sample:

@Service
class MyService(
  val repo: MyRepository // Injected from Spring
)

fun callDoSomething() {
  // `repo` is set when accessed from here
  println("Repo: $repo")
 
  // works
  update(case =  repo.getCase()) // works

 // throws NPE on runtime
  update()
}

fun doSomething(case: CaseBE = repo.getCase()) { // repo is null when accessed from parameter list
  // ...
}

Expected result:

Result of expression is assigned to parameter

Actual result:

Null-pointer exception because all injected properties are null for thiswhen evaluated as default parameter. Seems like the scope of the class is comlpletely lost which is highly unexpected.

It does not even work with an explictly scoped this:

fun doSomething(case: CaseBE = this@MyService.repo.getCase()) { // still NPE when accessing `repo`
  // ...
}

I even tried it with self-reference, same here:

@Service
class MyService(
  val repo: MyRepository // Injected from Spring,
  @Lazy self: MyService, // self-reference as attempted workaround
)

fun callDoSomething() {
  // `repo` is set when accessed from here
  println("Repo: $repo")
 
  // works
  update(case =  repo.getCase()) // works

 // throws NPE on runtime
  update()
}

fun doSomething(case: CaseBE = self.repo.getCase()) { // repo is null when accessed from parameter list
  // ...
}

I reported that issue to the Kotlin Team (https://youtrack.jetbrains.com/issue/KT-78600) but they immediately redirected me to here because they are convinced that this is an issue with Spring itself or the kotlin-spring plugin.

Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions