Ubiratan Soares - Software Engineer da Stone, fala sobre Kotlin : Advanced Tricks no Kotlin Community Summit 2018.
https://eventos.imasters.com.br/kotlinsummit/
Saiba mais em
4. fun validate(name: String) =
name.length in 2!"20
fun saveUser(name: String) =
validate(name)
.also { saveWith(name) }
Also
5. TakeIf
/#$
* Returns `this` value if it satisïŹes the
* given [predicate] or `null`, if it doesn't.
%&
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) '( Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}
6. TakeIf
/#$
* Returns `this` value if it satisïŹes the
* given [predicate] or `null`, if it doesn't.
%&
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) '( Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}
7. TakeUnless
/#$
* Returns `this` value if it _does not_ satisfy
* the given [predicate] or `null`, if it does.
%&
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeUnless(predicate: (T) '( Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (!predicate(this)) this else null
}
8. fun names() =
if (Random().nextBoolean()) "Elvis"
else "Presley"
val shortName =
names()
.takeIf { it.length )* 5 }
+, "Too long"
val longName =
names()
.takeUnless { it.length )* 5 }
+, "Too Short"
10. class DeepLinkParser {
fun parse(uri : String) : ProductId {
// Parse your URI and extract product id
}
}
11. class DeepLinkHandler(
val parser: DeepLinkParser) {
operator fun invoke(url : String) : Intent {
// Handle with parser and get your Intent
}
}
12. class DeepLinkHandler(
val parser: DeepLinkParser) {
operator fun invoke(url : String) : Intent {
// Handle with parser and get your Intent
}
}
13. Invoking Instances
val parser = DeepLinkParser()
val handler = DeepLinkHandler(parser)
val intent = handler("myapp:-.product/123456")
// Launch your Activity đ
14. A tiny web DSL
sealed class HTTPMethod
object GET : HTTPMethod()
object POST : HTTPMethod()
class Status {
var code: Int = 0
var payload: String = ""
}
class HttpRequest {
var method: HTTPMethod = GET
var body: String = ""
var query: String = ""
}
class HttpResponse {
var internalMessage: String = ""
lateinit var status: Status
}
15. class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun handle() {
-. TODO
}
}
20. class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun response(block: HttpResponse.() '( Unit) {
response = HttpResponse().apply { block() }
}
fun handle() {
-. TODO
}
}
21. class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun response(block: HttpResponse.() '( Unit) {
response = HttpResponse().apply { block() }
}
fun handle() {
-. TODO
}
}
đ
22. class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun response(block: HttpResponse.() '( Unit) {
response = HttpResponse().apply { block() }
}
fun handle() {
-. TODO
}
}
class HttpResponse {
var internalMessage: String = ""
lateinit var status: Status
fun status(setup: Status.() '( Unit) {
status = Status().apply { setup() }
}
}
23. class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun handle() {
-. TODO
}
}
class HttpResponse {
var internalMessage: String = ""
lateinit var status: Status
operator fun invoke(
setup: Status.() -> Unit) {
status = Status().apply { setup() }
}
}
24. endpoint("/api/product") {
request {
method = POST
body = "{ Some json }"
}
response {
code = 200
payload = "{ Some json }"
}
}
endpoint("/api/product") {
request {
method = POST,
body = "{ Some json }"
}
response {
status {
code = 200
payload = "{ Some json }"
}
}
}
Before After
34. The Nothing Type
https://en.wikipedia.org/wiki/Bottom_type
" In type theory, a theory within mathematical logic,
the bottom type is the type that has no values. It is also
called the zero or empty type, and is sometimes denoted
with falsum (â„).
A function whose return type is bottom cannot return any
value. In the CurryâHoward correspondence, the bottom
type corresponds to falsity. "
35. /#$
* The type with only one value: the Unit object.
* This type corresponds to the `void` type
* in Java.
%&
public object Unit {
override fun toString() = "kotlin.Unit"
}
37. /#$
* Always throws [NotImplementedError]
* stating that operation is not implemented.
%&
@kotlin.internal.InlineOnly
public inline fun TODO(): Nothing =
throw NotImplementedError()
38.
39. Nothing and ïŹow control
inline fun <T> guard(
receiver: T?,
block: () '( Nothing): T {
if (receiver 12 null) { block() }
return receiver
}
https://gist.github.com/hzsweers/463500043b1a9708ba4e26c7ad1862fd
40. fun guarding() {
val conference: String? = "Kotlin Summit"
val guarded = guard(conference) { return }
val guardedAgain = guard(conference) {
throw IllegalStateException("Null konf")
}
val invalid = guard(conference) {
-.Compiler error because not
-.returned or thrown an exception!
}
}
41. Nothing and Generics
sealed class Tree<out T>
class Node<T>(
val left: Tree<T>,
val right: Tree<T>) : Tree<T>()
class Leaf<T>(val value: T) : Tree<T>()
object Empty : Tree<Nothing>()
42. val tree = Node(
Leaf("1"),
Node(
Leaf("2"),
Empty
)
)
1
2
43. sealed class Result<out V, out E>
data class Value<out V>(val value: V) :
Result<V, Nothing>()
data class Error<out E>(val error: E) :
Result<Nothing, E>()