'Property with return value in Java/Kotlin?

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!



Solution 1:[1]

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().

Solution 2:[2]

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
    }

Solution 3:[3]

You can also use lazy initialization property

val someProperty: SomeType by lazy {
        // create a default value for someProperty inside this closure
        // someValue must be of the same type as SomeType
        SomeType(param1, param2, ...)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ivo Beckers
Solution 3 Vraj Shah