Sandeep Chandra
04/06/2021, 9:29 AMI have just started looking at Kotlin, I have been using F# on .NET for a while now and I am liking Kotlin. I am missing pipe operator in Kotlin though, is there any plan to bring the pipe operator to Kotlin?
raulraja
04/06/2021, 9:47 AMelizarov
04/06/2021, 11:19 AM.call
style, e.g. collection.filter {...}.map{...}
(no need for a pipe here)
2. Kotlin has .let
scope function that covers the case for non-extension functions, e.g. collection.first().let { println(it) }
wakingrufus
04/06/2021, 4:27 PMinfix fun <A, B> A.`|`(nextOp: (A) -> B): B {
return nextOp(this)
}
fun test(): Int {
return " " `|` String::length `|` " "::repeat `|` String::length
}
fun test(): Int {
return " ".let(String::length).let(" "::repeat).let(String::length)
}
and then
fun test(): Int {
return " ".length.let(" "::repeat).length
}
in ideomatic kotlin?Sandeep Chandra
04/06/2021, 8:58 PMlet square x = x * x
[1..100]
|> List.map square
square
and a list of numbers from 1..100 and then I call the List.map passing in square
function. The pipe operator passes list of numbers to List.map, the map function takes 2 arguments. With pipe operator the value piped
is passed as last argument to the function.raulraja
04/06/2021, 9:07 PMfun square(x: Int) = x * x
val result = (1..100).map(::square)
It gets more complex as your functions are polymorphic and callable references have more than one type arg in my experience but similar style can be used with them. https://kotlinlang.org/spec/expressions.html#callable-referencesfold
or similar with more than one type argument as callable reference value to another function. In most cases you’d have to ascribe the types manually of the calling function so it takes exactly the shape it expects.|>
as a library you’d still need to declare N variations of the operator for as high of a function arity you want to support.Marius Kotsbak
04/21/2021, 10:57 AMelizarov
04/22/2021, 9:42 AM