Functions as arguments wiki entry


#1

On this page

http://confluence.jetbrains.net/display/Kotlin/Function+literals

I find that this bit of code

``

fun max<T>(collection : Collection<out T>, less : (T, T) -> Boolean) : T? {
  var max : T? = null
  for (it in collection)
  if (max == null || less(max, it))
           max = it
  return max
}

does not compile.  Screenshot of what the IDE says is attached.

Also, what does the “out” in Collection<out T> do?



funargs.png (71.3 KB)

#2

In line "if (max == null || less(max, it))" you pass variable max (type: T?) to function less that receives two not nullable arguments, so you should use .sure() function: "if (max == null || less(max.sure(), it))" . It is safe, because "less(max.sure(), it)" will be computed only if max != null.


#3

About out you can read at http://confluence.jetbrains.net/display/Kotlin/Generics in section Variance.

In a few words, Collection<out T> means that we only can get T from the collection, but can’t put T into the collection.


#4

Frostman wrote:

In line “if (max == null || less(max, it))” you pass variable max (type: T?) to function less that receives two not nullable arguments, so you should use .sure() function: “if (max == null || less(max.sure(), it))” . It is safe, because “less(max.sure(), it)” will be computed only if max != null.


Thanks!  Since your reply, my plugin automatically updated, and now the IDE is much more precise, before runtime, about what the problem is.  Screenshot attached.

And if I use “max.sure()” as you suggest, all the red in the IDE goes away.

Maybe I expect too much, but if max is null, the code after the OR  is not going to execute.  Which means in the post-OR part the IDE/compiler could relieve me of typing max.sure().  No?



funargs1.png (100 KB)

#5

Frostman wrote:

About out you can read at http://confluence.jetbrains.net/display/Kotlin/Generics in section Variance.

In a few words, Collection<out T> means that we only can get T from the collection, but can’t put T into the collection.


Thanks.

I find I have to read about generics really carefully and slowly, otherwise I get really confused.  I find the finer points of Java generics somewhat odd, and I can’t figure out whether I have a mental block about all generics, or whether generics in Java are just weird.  Either way, I find generics beyond trivial use cases, well, somewhat scary.  It’s not so much that I cannot “memorize” the rules.  It’s more about the need to know why the rule in the first place.  Hope that makes sense.


#6

Maybe I expect too much, but if max is null, the code after the OR  is not going to execute.  Which means in the post-OR part the IDE/compiler could relieve me of typing max.sure().  No?

The problem is that max is mutable, so we can't guarantee it won't change...