Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a String to a Symbol in Runtime in Scala?

I have a case class that looks like this:

case class Outcome(text: Symbol)

Now I need to change the value of text at runtime. I try to do something like this:

val o2 = o1.copy(text.name = "foo" ++ text.name)

This obviously gives me a compilation error:

type mismatch; found : String required: Symbol

How can I convert a symbol to string, append/prepend something and again change it to a symbol? Or to be more simple, how can I change the name of a symbol?

like image 544
Core_Dumped Avatar asked Dec 26 '13 12:12

Core_Dumped


1 Answers

You could use Symbol.apply method:

Symbol("a" + "b")
// Symbol = 'ab

val o2 = o1.copy(text = Symbol("foo" + o1.text.name))

There is a useful tool to work with nested structures in scalaz - Lens

import scalaz._, Scalaz._

case class Outcome(symbol: Symbol)
val symbolName = Lens.lensu[Symbol, String]( (_, str) => Symbol(str), _.name)
val outcomeSymbol =
  Lens.lensu[Outcome, Symbol]( (o, s) => o.copy(symbol = s), _.symbol)
val outcomeSymbolName = outcomeSymbol >=> symbolName

val o = Outcome('Bar)

val o2 = outcomeSymbolName.mod("foo" + _, o)
// o2: Outcome = Outcome('fooBar)
like image 93
senia Avatar answered Oct 16 '22 19:10

senia