https://kotlinlang.org logo
#announcements
Title
# announcements
r

Raymond Barlow

11/07/2019, 4:41 AM
is there a `const()`funciton in Kotlin? (or equivalent)
b

benleggiero

11/07/2019, 5:05 AM
Can you give an example in a language you're more familiar with?
k

kevindmoore

11/07/2019, 5:59 AM
There is the const keyword. What are you trying to achieve?
r

Raymond Barlow

11/07/2019, 11:44 AM
Sure: Haskell:
const x _ = x
Scala:
const(a: A) = _ => a
I can, of course define it myself. Just wondering if it is already defined in the standard libraries.
m

Mike

11/07/2019, 1:01 PM
Some ideas here for an identity function, including
{ it }
. So no built-in identity function, but depending on scenario, some succinct ways to accomplish it.
👍🏼 1
r

Raymond Barlow

11/08/2019, 6:47 PM
But what about const?
m

Mike

11/08/2019, 7:30 PM
What am I missing?
const
looks like it is a function that returns the passed parameter. Identity does the same thing, so aren't they equivalent, just a different name?
r

Raymond Barlow

11/09/2019, 10:53 AM
The difference is that
identity()
returns what it is given when called.
const(a)
will always return the value
a
, no matter what the input.
const(5)
would be the same as
{ _ -> 5 }
like I said, easy enough to define my own, but it seems like it should be a core function
listOf(1,2,3).map(identity()) == listOf(1,2,3)
1
listOf(1,2,3).map(const(5)) == listOf(5,5,5)
1
b

benleggiero

11/12/2019, 4:41 AM
Aha, I see. I like this idea, and I think that it would have a place in the stdlib. Maybe submit a PR?
r

Raymond Barlow

11/12/2019, 8:15 AM
ok cool 🙂
m

Mike

11/12/2019, 11:13 AM
Thank you for the explanation. The syntax for defining it didn't make it clear the function would always return the same value. So now I understand the difference, but I'm not grasping the use case for it. Time for me to do some research...
3 Views