Home > Enterprise >  Property with return value in Java/Kotlin?
Property with return value in Java/Kotlin?

Time:12-03

This is a pretty basic question, but I haven't been able to find any answer on SO yet.

I'm just curious, is there a corresponding way in Java or Kotlin to write a property with a return value, such as there is in Swift:

class SomeClass {
    let someProperty: SomeType = {
        // create a default value for someProperty inside this closure
        // someValue must be of the same type as SomeType
        return someValue
    }()
}

Documentation link: https://docs.swift.org/swift-book/LanguageGuide/Initialization.html#ID232

Many thanks in advance!

CodePudding user response:

I'm not familiar with Swift, but if I understand correctly that the closure/lambda is invoked immediately to set an initial value to the property, then this is as simple as:

var someProperty = someValue

And if someValue is a result of a more complicated logic that can't be represented as a simple expression, then:

var someProperty: SomeType = run {
    ...
    someValue
}

As a fact, the provided Swift code is almost a valid Kotlin code as well. We don't have to use run(), we can create a lambda and invoke it immediately, as in Swift:

var someProperty: SomeType = {
    ...
    someValue
}()

However, this is not considered "the Kotlin way" and IntelliJ IDE even suggest to replace it with run().

CodePudding user response:

I think a custom getter is maybe what you are looking for?

val someProperty: SomeType
    get() {
        // create a default value for someProperty inside this closure
        // someValue must be of the same type as SomeType
        return someValue
    }
  • Related