Kotlin Standard lib contains the 'with' method that receives an object and a method of that object defined as:
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
And can be used as:
val str = "string"
with(str) {
println(size)) // will print 6; equals to "string".size
println(substring(3)) // will print (ing); equals to "string".substring(3)
}
How to define similar method in Scala?
Though both Scala and Kotlin are interoperable with Java, Kotlin leads the show if you wish to maintain full compatibility with existing Java-based projects and technologies. Kotlin is designed to be 100% interoperable with Java. So, you can easily call Kotlin code from Java and vice-versa effortlessly.
Kotlin focuses on a better version of Java by reducing the boilerplate code and new features like null safe design. In comparison, Scala offers a flexible syntax motivated by functional programming ideas. Before we compare them both, have a look at their overview and salient features.
While both these JVM languages are known for the functional programming paradigm, Scala is the winner between Kotlin vs Scala in terms of functional programming. Let's see, Compared to Kotlin, Scala is more affected by functional programming languages such as Haskell.
Kotlin is inspired by existing languages such as Java, C#, JavaScript, Scala and Groovy.
There is no way to define such a method in Scala, because the concept of function literals with receiver does not exist in Scala.
However, Scala's import
is general enough that you can use it instead of with
. Your example would write as:
val str = "string"
import str._
println(length)
println(substring(3))
Note that size
specifically does not work with this scheme because it happens to be implicitly pimped on String
, so I had to use length
instead. However, in general, this is the pattern we use.
Edit after comment: if you want to explicitly scope the import to a portion of your code, you can do so with braces, which are always allowed to scope things:
val str = "string"
{
import str._
println(length)
println(substring(3))
}
println(length) // does not compile
Note that the blank line is necessary, otherwise it will be parsed as trying to call the apply
method on "string"
with the {...}
as argument. To avoid this problem, you can use the locally
method:
val str = "string"
locally {
import str._
println(length)
println(substring(3))
}
println(length) // does not compile
locally
per se doesn't do anything; it is only used to visually highlight that the braces are there only for scoping reasons, and by extension to help parsing do the right thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With