How do I give a function as the default argument on an interpreter?

Asked 5 months ago, Updated 5 months ago, 11 views

On kotlin's command-line interpreter (kotlinc-jvm1.1.2-2), first define the function id and

>> funid(x:Int)=x

Then I tried to define the function applyTo10 and got an error.

>>fun applyTo10(f:(Int)->Int=:id)=f(10)
error:left-hand side of a callable reference with a receiver parameter cannot be empty. Please specify the type of the receiver before'::'explicitly
fun applyTo10(f:(Int)->Int=::id)=f(10)

If you follow the error message, you can specify the receiver type, but I don't know what the receiver type is in this case.

By the way, if you give a lambda expression instead of a function reference, there is no error.

>>fun applyTo10(f:(Int)->Int={it})=f(10)

How do I specify a function of the default argument by name (id in this case)?

The compromise plan is to use the name in the Lambda formula.

fun applyTo10(f:(Int)->Int={id(it)})=f(10)

and so on.


2022-09-30 14:19

2 Answers

If you write definitions in Kotlin's REPL in order, it will be processed differently (probably) from the program you compile on Kotlinc, so I think that's the reason.The Line1 in the answer is probably a class or object that has something to do with the id defined in the first line, but I don't think it's usually expected to refer to it, so I can't help it.

Why don't you wrap it in object as shown below?

Welcome to Kotlin version 1.1.0 (JRE 1.8.0_111-b14)
Type:help for help,:quit for quit
>> object W {
...   funid(x:Int)=x
... }
>> fun applyTo1o(f:(Int)->Int=W::id)=f(10)

Also, I experimented with Line1 and Line2.

Welcome to Kotlin version 1.1.0 (JRE 1.8.0_111-b14)
Type:help for help,:quit for quit
>>> fun add(x:Int, y:Int) = x+y
>> > fun sub(x:Int, y:Int) = x-y
error:the integer literal does not conform to the expected type Line 1
error:no value passed for parameter

>>a (Line 1(), 1, 2)
>>s (Line 2(), 1, 2)
java.lang.NoSuchMethodError: Line 2: method<init>()V not found

As far as this result is concerned, the class that holds information such as functions defined in each row of REPL is LineN
I think it looks like (Line2() dies with a runtime exception is a bit of a mystery)

2022-09-30 14:19

What about this?

fun applyTo10(f:(Int)->Int=this::id)=f(10)

2022-09-30 14:19

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.