I am using the following implicit class
in order to call a function which would otherwise take parameters without having to write the parameters in brackets:
scala> implicit class Print(string: String) {
| def echo: Unit = Console.println(string)
| }
defined class Print
scala> "Hello world" echo
Hello world
However while this works, I don't really like how it looks and my goal is to get the method call in front of the input variable as I think it reads better.
Is there any simple way, without relying on external libraries, to be able to call a method before supplying the parameters and without needing brackets? Implicit classes are what I've been using so far but that doesn't have to be the final solution.
What I would like to type instead of "Hello world" echo
:
scala> echo "Hello world"
Alternatives I have tried:
- Object with
apply
method
Requires parentheses
object echo {
def apply(string: String): Unit = Console.println(string)
}
echo "Hello world" // Error: ';' or newline expected
- extending
Dynamic
[see here]
Doesn't seem to work in my version of Scala
- Special characters [see here]
Looks ugly and not what I am looking for
- Scalaz [see here]
Looks to do basically what my implicit class
solution does, and I don't want any external dependencies.
EDIT
This answer has been pointed to as a potential solution, but again it doesn't address my issue as it relies on Dynamic
to achieve a solution. As previously mentioned, Dynamic
does not solve my problem for a couple of reasons:
- It behaves funnily
If you define a val and try to println that val, it gives you back the val's name and not its value (as pointed out by @metaphori):
object println extends Dynamic {
def typed[T] = asInstanceOf[T]
def selectDynamic(name: String) = Console.println(name)
}
val x = "hello"
println x // prints: x
- The specific example linked to did not work when I tried to recreate it - it still gave the
';' or newline expected
error
If I just misunderstood how to implement it then I would appreciate a scalafiddle demonstrating that this solution solves my problem and will happily concede that this question is a duplicate of the previously mentioned answer, but until then I do contest it.