is there a `const()`funciton in Kotlin? (or equiva...
# announcements
r
is there a `const()`funciton in Kotlin? (or equivalent)
b
Can you give an example in a language you're more familiar with?
k
There is the const keyword. What are you trying to achieve?
r
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
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
But what about const?
m
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
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
Aha, I see. I like this idea, and I think that it would have a place in the stdlib. Maybe submit a PR?
r
ok cool 🙂
m
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...