EventCallback<Float> { if (it > 0) printl...
# announcements
i
EventCallback<Float> { if (it > 0) println("ouch!") else println("1") } I don't understand the syntax, put a type before a lambda, is ?
s
How familiar are you with generics
you’re not putting a type before a lambda, you’re passing in a type parameter to a genericized function
i
I know generics, but I don't know how generics work with lambda
s
have you looked at this particular function definition?
if I had to guess it probably looks something like this
Copy code
fun <T> EventCallback<T>(block: (T) -> Unit)
i
"""
object : EventCallback<Float> { override fun onEvent(arg0: Float): Unit = if (arg0 > 0) println("ouch!") else println("1")
s
that looks more accurate, actually,
EventCallback<T>
would be an interface
in this case a SAM interface
you also want to use triple backticks ` ``` ` to wrap code, and shift-enter to insert newlines without sending messages
i
Copy code
object : EventCallback<Float> {
            override fun onEvent(arg0: Float): Unit = if (arg0 > 0) println("ouch!")
             else println("1")
I don't know this stuff turn to
Copy code
EventCallback<Float> { if (it > 0) println("ouch!") else println("1") }
s
so if you ctrl/cmd+b into EventCallback you’ll see the definition of the interface
probably looks like this if I had to guess
Copy code
public interface EventCallback<T> {
  void onEvent(T arg0);
}
with a single method defined, making it a Single Abstract Method interface, which can be converted to a lambda
i
aha,
s
Kotlin lets you implement SAMs with a single lambda because it can substitute in for that single method
you need to provide a parameter for
T
if it can’t be inferred
i
ok
s
you could probably do something like this if you wanted
Copy code
EventCallback { param: Float ->
  if (param > 0) println("ouch!") else println("1")
}
i
what this `it' here means?
should it be param?
you really should read through the docs if you haven’t already
i
fine
but your code is ```
Copy code
param: Float ->
  if (it > 0)
s
That might not work actually, depends on if type inference is smart enough in this case
i
I thought it should be
Copy code
it: Float ->
if (it>0)
s
you can explicitly type
it
or you can pass an explicit parameter to the interface
ah I see
I typo’d, my bad
i
this lambda stuff in kotlin seems wonderful!
s
They’re pretty great, I’d consider their use to be a defining feature of the language
i
aha "That's because Kotlin has SAM ("single abstract method") only for Java interfaces."