I was trying to learn higher order functions from the first example of this video. Here's my code and output.
Code
fun lowercase(value: String) = value.toLowerCase()
fun higherOrder(value:String, op: (String) -> String) : String {
println("Executing higher order fun $op")
return op(value)
}
fun main(args: Array<String>) {
println(higherOrder("HELLO", ::lowercase))
println(higherOrder("hello", {it -> lowercase(it)}))
println(higherOrder("HeLlo", { x -> lowercase(x) }))
println(higherOrder("Hello", { lowercase(it) }))
}
Output
Executing higher order fun function lowercase (Kotlin reflection is not available)
hello
Executing higher order fun Function1<java.lang.String, java.lang.String>
hello
Executing higher order fun Function1<java.lang.String, java.lang.String>
hello
Executing higher order fun Function1<java.lang.String, java.lang.String>
hello
Process finished with exit code 0
So my question is, why does it print Kotlin reflection is not available?
In Kotlin, Reflection is a combination of language and library capabilities that allow you to introspect a program while it's running. Kotlin reflection is used at runtime to utilize a class and its members, such as properties, methods, and constructors.
?: takes the right-hand value if the left-hand value is null (the elvis operator). :: creates a member reference or a class reference.
The KClass type is Kotlin's counterpart to Java's java. lang. Class type. It's used to hold references to Kotlin classes; you'll see what it lets you do with those classes in the “Reflection” section later in this chapter. The type parameter of KClass specifies which Kotlin classes can be referred to by this reference.
KProperty1. Represents a property, operations on which take one receiver as a parameter. interface KProperty1<T, out V> : KProperty<V>, (T) -> V. Common. JVM.
Full reflection requires the kotlin-reflect
library in addition to kotlin-stdlib
.
If full reflection is available it will probably have a more comprehensive toString()
, hence the message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With