Reputation: 7845
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?
Upvotes: 10
Views: 1588
Reputation: 22085
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.
Upvotes: 18