How specify type for generic var


#1

class Socket { var <T>message:((data:T)->Any)? = null; }

class JsonRpcServer(socket:Socket) {
  socket.message = {data ->
  }
}

How I can specify type (see screenshot

)?


#2

does this work...

socket.message = {data: String ->
  “Hello $data”
}


#3

data: String is incorrect in any case, must be

(data:String):Any?

but it is not working too, “Not enough data to compute value …”


#4

What do you mean by "generic var"? What's the expected behavior?


#5

I mean "var <T>message:((data:T)->Any)? = null;"

What I want: declare a variable to hold the callback. callback must be typified.
How I can assign value to “message” variable? I cannot find any way.


#6

So, you need a property that can hold a function of type (T) -> Any? for any T.

This doesn’t sound right:

message<String> = {s -> s.length()}
message<Int>(1) // what behavior do you expect here?

Looks like you want this variable to hold a generic function (as opposed to assign a function to a generic property). This is not supported in the current type system.


#7

>> you need a property that can hold a function of type (T) -> Any? for any T. Yes.

If we set message to callback that accept only String, so, any invocation with inappropriate param type must be failed.


#8

What do you mean by "failed"? Exception at runtime? This is against the ideology of a statically typed language. User should always explicitly call for trouble by using casts if something should break at runtime.


#9

I am writing json-rpc (wrapper around SockJS). If server send incorrect data — will be error in runtime (I cannot find any way do invocation by kotlin, currently, it is done by javascript side (native js function)).

Hmm… You are right. Thanks. We must specify message data type in class declaration:

class Socket<T>(uri:String) {   var message:((data:T)->Any)? = null }