"how to convert a string from a text input into a function in a scala" Code Answer


you want to compile the line of code that the user enters, with some useful preamble.

i haven't done this so i don't have a snippet handy (but try searching), but you can embed the repl, have it compile the line of code, and then extract the result.

here is a snippet that uses iloop to get some output, but you want to use imain to get a result with the result class that wraps the user function.

import scala.tools.nsc.interpreter.iloop
import java.io.stringreader
import java.io.stringwriter
import java.io.printwriter
import java.io.bufferedreader
import scala.tools.nsc.settings

object funcrunner extends app {

  val line = "sin(2 * pi * 400 * t)"

  val lines = """import scala.math._
    |var t = 1""".stripmargin

  val in = new stringreader(lines + "n" + line + "nval f = (t: int) => " + line)
  val out = new stringwriter

  val settings = new settings

  val looper = new iloop(new bufferedreader(in), new printwriter(out))
  val res = looper process settings
  console println s"[$res] $out"
By superm4n on July 27 2022

Answers related to “how to convert a string from a text input into a function in a scala”

Only authorized users can answer the Search term. Please sign in first, or register a free account.