I am VERY new in Kotlin and still giving my first steps. Coming from Java I heard “is very similar” … but well, for me it is not
I found trying to understand this code.
sealed class User {
}
data class ActiveUser(val name: String, val lastName: String, val email: String) : User () {
fun <T> doSomething(nickname: String.() -> T?) =
nickname(this.email) ?: throw RuntimeException("Error")
}
so far I undertood this:
Sealed class is an abstract class used to handle inheritance in a better way.
ActiveUser class inherits from the sealed class and declare its own functions
doSomething accept one parameter of type string… THEN I get lost
This is the type of a function with zero arguments (because of the ()) that returns a T? (a nullable T, can be any type here, the way the function is defined).
And the String. at the start means, that the function has a String as additional special receiver parameter, so it can be executed like this: "MyString".name() instead of name("MyString") and the string value will be called this inside the method instead of having a parameter name. Like if you would add a method to the String class.
Your code is confusing because you have multiple things in scope that are called name (the function parameter and the user-name), you should probably fix that.
In Kotlin you can pass methods or lambdas as parameters. Under the hood, name implements a Function<> interface with an invoke method, similar to Java functional interfaces and name("String") is simply translated to name.invoke("String") or something similar by the compiler.
What is Kotlin specific is that inside the {} you’re essentially inside the String class because of the (String.(...)) and can execute all the methods, that String has without needing a String variable. this is essentially the object that sayHello passes as argument, in this case the user name.