1

I am new to Scala and have read threads related to String Interpolation.

My requirement is that , I want to find the type of an expression, before actually evaluating the expression. To make it clear:

val tesType = s"${{10 * Math.cos(0)+ 3}.getClass}"

This gives me the return type of the entire expression.

Is it possible to generalise this by replacing the actual expression by a variable containing the expression? Something like:

val expression="10 * Math.cos(0)+ 3"
val tesType = s"${{expression}.getClass}"

Would something like this be possible or I am totally wrong in thinking in this direction?

Thanks

6
  • You want type of expression which is String, right ? Commented Oct 30, 2015 at 14:48
  • Yes, once iterpolated, I want it to check for functions inside the string and give the result type accordingly.In the above case, double Commented Oct 30, 2015 at 14:51
  • String interpolation happens at compile time, nothing interpreted here. Also, I'd use variables as soon as your type gets a bit more complicated. Commented Oct 30, 2015 at 14:53
  • @Reactormonk string interpolation in general does not happen at compile time. That would require macros. Commented Oct 30, 2015 at 14:55
  • @0__ I think @Reactormonk referred to the fact that s"some $foo" will be replaced by something like StringContext("some ").s(foo) before actual compilation, but by the compiler. Commented Oct 30, 2015 at 15:26

2 Answers 2

2

It's not possible to do with string interpolation. What you actually want to do is to compile scala code in runtime from string (file etc).

For ex twitter Eval library can be used for this purposes: https://eknet.org/main/dev/runtimecompilescala.html

Sign up to request clarification or add additional context in comments.

Comments

0

If you want the expression to be in a string, then see mst's answer (you can also use scala-compiler itself as a library, but its API is harder to use).

If you have an expression as an expression, you can do

import scala.reflect.runtime.universe._
def typeOfExpr[T: TypeTag](t: => T) = typeOf[T]

typeOfExpr(10 * Math.cos(0)+ 3) // returns Double

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.