One question, in Typescript I’m able to do somethi...
# getting-started
c
One question, in Typescript I’m able to do something like this:
Copy code
type CustomReturnType = (a: String, b: Int) => String

export class Foo {
  private aggregator: CustomReturnType[] = [
    (a: String): String => a,
    (a: String, b: Int) => {
      ...
      return "something"
    }
  ]
}
On Kotlin, I did something like this:
Copy code
class Foo {
  var aggregator: MutableList<(a: String, b: Int) -> String> = mutableListOf()

  fun first(a: String): String {
    return a
  }

  fun second(a: String, b: Int) {
    ...
    return "something"
  }

  constructor() {
    aggregator.add(first)
    aggregator.add(second)
  }
}
Problem is I’m getting a Type mismatch
Required: (String, Int) -> String
Found: String
Does anyone know why I can’t or is there something I’m doing wrong?
t
I guess this is not actually your code anyway, because there are a couple of other problems with that code but i think I got your problem. The thing is that in JS it doesn't really matter how many parameters a function has. If it defines x parameters and you use less in the call, the trailing ones are just
undefined
(of course typescript could prevent this). If you put more parameters in the function call, they are just ignored. So in JS/TS, a function that only requires a single string parameter satisfies a declaration that provides an additional parameter (of any type). In Kotlin - like in most languages - functions aren't that flexible and can't be called with more or fewer parameters. For you to put a function reference in that list, it has to exactly match the declared signature, which
first
doesn't.
You could just get around this by defining a little lambda that calls that function:
Copy code
{ a, _ -> first(a) }
c
Yeah, that’s really clever! Thanks @Tobias Berger