Search code examples
scalaactor

how to execute (exec) external system commands in Scala actor?


to run an external command, I should

import sys.process._
val result="ls a" !

then when use actor, I need to also use "!" to send message. So ! is defined both in actor and in process, but I need to use them both in the same code block, how to do that?


Solution

  • I don't see the issue of Process and ActorRef both defining a method with the same name.

    An analog example would be

    class A { def ! = println("A") }
    class B { def ! = println("B") }
    val a = new A
    val b = new B
    a.! // "A"
    b.! // "B"
    

    There's no name collision or ambiguity at all.

    The only thing you have to worry about is the implicit conversion from String to Process.

    "foo".! works because Process is the only class in which String can implicitly be converted to that defines a ! method.

    As the documentation says, if you instead use something like "foo".lines, then the compiler gets confuse because it doesn't know whether to convert String to Process or to StringLike, since both define a lines method.

    But - again - this is not your case, and you can safely do something like:

    "ls".!
    sender ! "a message"
    

    and the compiler should not complain.