Kotlin, first steps! Part. 2

in #kotlin6 years ago

Hello Steemers!!!

Today we will talk a little more about Kotlin continuing our series first steps.

Extension Methods

Similar in other languages, Kotlin can declare methods on types you do not control, for example:

fun String.hello(): String{
 return “Hello ${this}”
}

val x = "Kotlin"
print(x.hello()) // prints "Hello Kotlin"

In this case it was declared a method inside the String type, an example more inside the Android world would be this:

fun ImageView.load(url: String){
  Picasso.with(context).load(url).into(this)
}

Now any ImageView can call the load method and load an image passing a url.

Extensions bring a great gain in readability, since it prevents us from having to write the notorious Utils (StringUtils, FileUtils, etc), which surely every Android developer should have written some day.

Data class

As the name itself says, classes are responsible for grouping data into a type of semantics, similar to what AutoValue makes, but in a much more elegant way:

data class Contact(val name:String,val cellNumber: String)

This class already provides methods like equal, hashCode, toString, and clone.

Default arguments

With this feature we can predefine value to an attribute:

// method declaration
fun Activity.toast(message: String, duration: Int =   Toast.LENGTH_LONG){
  Toast.makeText(this,message,duration).show()
}
// constructor of a class
class Contact(val email: String, val active: Boolean = true)

This way, the method only receives the parameter message mandatory and the duration is optional, so if you do not want to use that value that was set as the default, you can call the method with a parameter or two:

toast("Hello Kotlin")
//or
toast("Hello Kotlin" , Toast.LENGTH_SHORT)

-------<>-------|-------<>-------|-------<>-------

It's just for today. See you next time.

Github

Another way to learn a programming language for sure is to see open source codes and with the absolute certainty Github is the perfect place, now go to the link below:

https://github.com/topics/kotlin

Sort:  

Hello! Your post has been resteemed and upvoted by @ilovecoding because we love coding! Keep up good work! Consider upvoting this comment to support the @ilovecoding and increase your future rewards! ^_^ Steem On!

Reply !stop to disable the comment. Thanks!

Coin Marketplace

STEEM 0.18
TRX 0.13
JST 0.028
BTC 57630.83
ETH 3105.65
USDT 1.00
SBD 2.33