Hi, I have a very strange syntax (no)issue: do you...
# getting-started
g
Hi, I have a very strange syntax (no)issue: do you have any idea why in the myFun call in main(), I can use whatever arg in the last position? I would expect to be a correct expression for Int only as method is (I, String) -> Int
Copy code
fun main() {
  myFun(I::class.java, I::myMethod, true)
}

fun <P1, P2, R> myFun(
  klass: Class<P1>,
  method: (P1, P2) -> R,
  result: R
) {
  println("ok")
}

interface I {
  fun myMethod(a: String): Int
}
j
Because
R
isn't constrained. So the compiler can choose that
R==Any?
(In the most extreme case), and so any method return type for the second argument will be ok with any 3rd argument type. If you pass
myMethod
from
I
which returns
Int
, it's still valid if the compiler decides that
R==Any
, because
Int
is a subtype of any. And
Boolean
is also a subtype of
Any
Note that you can pass specific type arguments to
myFun
using angles brackets, which would force the conpiler's hand:
myFun<.., .., SpecificTypeHere>(...)
Usually this is not useful though, because you usually want to constrain the callers by crafting the definition itself
g
Oh, I see, Thx. Is there a way to do what I want to achieve? (basically that the last arg must have a type compatible with the return type of method)?
j
Not really, because theoretically it already does this.
Int
is
Any
no matter what. Do you have a more concrete real life use case where you need this? In general this hasn't turned out to be a problem for me, because usually
R
appears somewhere else that the called cares about, like a return value. If this is inferred to
Any
, they won't be able to do anything with it anyway, unless it's enough for them, on which case there is no problem
g
I'm building a distributed workflow engine. The interface represents the contract of a remote service. In another server there is an actual implementation of the "I" interface that runs the method. Now, I want to provide to users a syntax for completing an already submited remote method call. I wanted that this syntax checks the type of the given response to avoid sending bad data to the remote server. So basically, given an interface (that I do not control) and a method, I'd like the type system to check that a given object has the right type