https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dave08

11/14/2021, 10:57 AM
Given:
Copy code
class Foo(val bar: Bar)
class Bar(val baz: String)


val foo = Foo(Bar("baz"))

// why isn't this possible?
val bazGetter = Foo::bar::baz

// whereas this is ok?
val bazGetter2: (Foo) -> String = { it.bar.baz }
j

Joffrey

11/14/2021, 11:10 AM
Property references are not the same as lambdas technically. They can be more than just invoked, they are an actual description of the property. You can reference the property
Bar::baz
but not in the context of a particular
Foo
d

dave08

11/14/2021, 11:40 AM
Thanks for the explanation! I would have still expected that
Foo::bar::baz
would be the equivalent to
Bar:baz
as the description of the property the
Foo::
being used just to traverse to it... but I guess that wouldn't make sense when the lambda interpretation is different...
s

smit01

11/14/2021, 2:35 PM
class Foo(val name:String="none") class Bar(val far:Foo = Foo()) ((Bar::far)(Bar("smit"))::name)
🙈 1
😮 1
d

dave08

11/14/2021, 2:44 PM
That's a bit overkill (and I don't think it would work in my case...), I needed this for strikt's
get(Foo::prop)
function, to avoid
get { it.bar.baz }
which goes through the source files to get the name..., but thanks anyways!
e

ephemient

11/15/2021, 5:38 AM
arrow lens also provides a way to compose getters, but if your use case requires a direct property reference then none of these will work
4 Views