Going From Python to Kotlin: 10 Language Features to Know | by Raimi Karim | Feb, 2022

Python

if individual is None:
return ""
else:
return f"howdy, individual.identify"

Kotlin

return individual?.let  "howdy, $it.identify" : ""

Discover how individual is rigorously accessed (through the protected name operator ?.).

🎁 What does this language characteristic provide?
Security, concision

💡 How is it carried out?
nullable varieties, protected calls ?., non-null assertions !!, and the Elvis operator ?: amongst others, scoped capabilities like let.

In Python, it’s typically not idiomatic to cross capabilities round (“first-class residents”), though I’ve seen some like in Keras the place you outline a operate for the metric you need to be printed out.

As a result of it’s not idiomatic, I’d wish to share it with you right here utilizing Kotlin for example.

Right here’s a contrived instance (let me know when you can provide you with a greater instance!) the place we print a abstract statistic (outlined as metric) given an inventory of numbers (information).

enjoyable printSummary(information: Record<Float>,
metric: (Record<Float>) -> Float)
val abstract = metric(information)
println(abstract)

Seeing it in motion:

printSummary(myList)  x ->
x.sum() / x.measurement

Discover the trailing lambda syntax (for distinction) and the nameless operate.

🎁 What does this language characteristic provide?
Flexibility, readability, concision

💡 How is it carried out in Kotlin?
nameless capabilities, higher-order capabilities, trailing lambda syntax

In Python, we seldom use useful programming verbs like map, scale back and filter for collections (“assortment strategies”) to chain them collectively (“fluent interface”). It is because listing comprehension (and dictionary comprehension) and array programming syntax are extra idiomatic.

This implies we’re not uncovered to this language characteristic.

Suppose you need to rework an inventory of [1,2,3] by including 3 to every component and solely take the even quantity outcomes.

In hypothetical Python, it seems to be like this:

my_list.map(lambda x: x+3).filter(lambda x: xpercent2==0)

In Kotlin, it seems to be like this

myList.map  x -> x+3 .filter  x -> xpercent2==0 

which reads properly from left to proper for my part.

Word that right here’s how you’ll do it in Python, although not idiomatic (and unreadable):

listing(filter(lambda x: xpercent2==0, map(lambda x: x+3, my_list)))

Word that right here’s how you’ll do it in Python, although not idiomatic (and unreadable):

🎁 What does this language characteristic provide?
Readability

💡 How is it carried out in Kotlin?
Verbs carried out through strategies of assortment courses.

Do you know which you could add a operate to an current class from the usual library or an imported library?

Suppose you need to get hold of the time for the reason that epoch (Unix time). That is how it could appear to be in hypothetical Python. I’m going to rename the datetime class to Datetime (sure, datetime is a category!):

from datetime import Datetimedef Datetime.get_epoch_now():
return this.strtime("%s").toInt()

Discover how I casually ‘prolonged’ the Datetime class to incorporate a brand new methodology referred to as get_epoch_now.

Extension capabilities are a neat characteristic in Kotlin as a result of it permits you to ‘park’ associated strategies collectively.

🎁 What does this language characteristic provide?
Readability

💡 How is it carried out in Kotlin?
Carried out through class extensions

A domain-specific language, or a DSL, is a language outlined by the programmer in order that different programmers can use it to realize their goal.

Python doesn’t have this.

The instance under exhibits a syntax that appears completely different from the same old Kotlin (seems to be JSON-ish as a substitute). However this syntax is legitimate. Taken from https://github.com/zsmb13/VillageDSL.

val newVillage = village 
home
individual
identify = "Emily"
age = 31

individual(identify = "Hannah")
age = 27

individual("Alex", 21)

I believe this language characteristic is thrilling as a result of you may get inventive with it whereas additionally fascinated by the consumer code or the individuals who will use it.

🎁 What does this language characteristic provide?
Flexibility, readability

💡 How is it carried out in Kotlin?
Kind-safe builders through infixes methodology names of a category

Do you know you possibly can outline operate or methodology names with areas 😱 ?!

Kotlin permits this (enclosed with backticks):

enjoyable `do one thing`() 

...

and also you name it like this:

`do one thing`()

Whereas that is normally solely meant for writing take a look at capabilities, this characteristic is useful, primarily as a result of take a look at names can get fairly lengthy.

Thanks, JetBrains, for being very considerate.

🎁 What does this language characteristic provide?
Readability

💡 How is it carried out in Kotlin?
Backtick syntax for take a look at operate names

The swap assertion is widespread in C-like languages. It’s like a number of if-else statements however with fewer phrases.

Let’s see how that is carried out utilizing when expression in Kotlin:

when x 
1 -> print("x == 1")
2 -> print("x == 2")
else -> print("x is neither 1 nor 2")

Word that Python 3.10 has one thing extra highly effective — structural sample matching (see here), which is just like the swap assertion but additionally analyses the sort (“sample”) of the thing.

🎁 What does this language characteristic provide?
Concision, Readability

💡 How is it carried out in Kotlin?
carried out through when

More Posts