Is there any way to override or overload = operator inside a class in Scala to implicitly converting data without defining implicit methods?
for example :
class A{
def =(str:String)={
.........
}
}
.........
val a=new A
a="TEST"
You can't override = in Scala because it is a language defined operator (like (, [ or <- are).
The only thing you can do is to use the update-method:
scala> :paste
// Entering paste mode (ctrl-D to finish)
class A {
var data = Map.empty[Int, String]
def update(i: Int, str: String) {
data += i -> str
}
def apply(i: Int): String =
data(i)
}
// Exiting paste mode, now interpreting.
defined class A
scala> val a = new A
a: A = A#77cb05b9
scala> a(5) = "hello"
scala> a(5)
res7: String = hello
But it is still not possible to leave out the parentheses in a(5) = "hello" because a = "hello" is the syntax to redefine a value. The shortest possible notation is a() = "hello", when you only specify the update-method like this: def update(str: String) {...}
See this blog post for a more detailed explanation on how to use the update-method.
According to the Scala Language Specification, section 1.1, = is a reserved word. You can't, therefore, override or overload it.
You can also use Scala-Virtualized, where you can override all control structures. This is nearly certainly overkill, but the option exists.
Related
When assigning a function using an unapplied method, it appears that named and default parameters are lost. Is there any way to avoid this?
def foo(namedParam: String = "defaultValue") = namedParam*2
// scala> foo()
// res8: String = defaultValuedefaultValue
def bar = foo _
// scala> bar()
// <console>:28: error: not enough arguments for method
// apply: (v1: String)String in trait Function1.
// Unspecified value parameter v1.
The reason I want to do this is to bundle my imports in a single file, i.e.
myproject/imports.scala
object imports {
def externalAPIFunction = myproject.somepackage.internalFunction _
}
scala shell
import myproject.imports._
externalAPIFunction() // no named or default arguments :(
Any way to do this or do I have to put my default arguments in the external function definition?
Functions (i.e. values of type Function<N>[...]) simply can't have default or implicit parameters in Scala, only methods can. And method _ returns a function: that's what it's for. So yes, to achieve your purpose you'd need to write
object imports {
def externalAPIFunction(namedParam: String = "defaultValue") =
myproject.somepackage.internalFunction(namedParam)
}
You can avoid duplication using
object imports {
val x = myproject.somepackage
}
// elsewhere
import myproject.imports._
x.internalAPIFunction()
// or
import myproject.imports.x._
internalAPIFunction()
which may or may not be good enough for your purposes.
I think you need to use currying.
def foo()(namedParam: String = "defaultValue") = namedParam * 2
//> foo: ()(namedParam: String)String
// scala> foo()
// res8: String = defaultValuedefaultValue
def bar() = foo() _ //> bar: ()String => String
bar() //> res0: String => String = <function1>
Here is the code:
trait MacApp {
def dockerIcon_=(s: String) = println("setting docker icon...")
}
object Main extends App with MacApp {
dockerIcon = "apple"
}
The scalac complains this:
Main.scala:6: error: not found: value dockerIcon
dockerIcon = "apple"
^
one error found
I see scala-swing library use _= a lot, e.g., https://github.com/scala/scala-swing/blob/2.0.x/src/main/scala/scala/swing/Label.scala#L28
Thanks!
You need both getter and setter:
scala> :pa
// Entering paste mode (ctrl-D to finish)
trait MacApp {
def dockerIcon_=(s: String) = println("setting docker icon...")
def dockerIcon = 42
}
object Main extends App with MacApp {
dockerIcon = "apple"
}
// Exiting paste mode, now interpreting.
defined trait MacApp
defined object Main
scala> Main main null
setting docker icon...
http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#assignments
Your expectations about the pair of members are established earlier at:
http://www.scala-lang.org/files/archive/spec/2.11/04-basic-declarations-and-definitions.html#variable-declarations-and-definitions
You're trying to assign to a function? I don't think that _= Swing code is using an operator, I think it's just an odd name...possibly for some obscure Java compatibility reason that escapes me at the moment.
But def defines a function, not a value, so you can't assign to it; you have to call it. Check out this console fragment:
scala> def text_=(s: String) = s + "foo"
text_$eq: (s: String)String
scala> text_=("bar")
res3: String = barfoo
I have a class which defines a private maintenance method synch, which I want to always be invoked whenever any other method of the class is invoked. The classic way of doing this would of course be:
def method1 = {
synch
// ... do stuff
}
def method2 = {
synch
// ... do other stuff
}
However, is there any way to have this done implicitly, so that I do not have to invoke it explicitly like I do above?
EDIT:
If it is possible to do this, is it also possible to define if I want the synch method to be called after or before each other method?
You could create your custom wrapper using def macros and Dynamic like this:
import scala.reflect.macros.Context
import scala.language.experimental.macros
def applyDynamicImplementation(c: Context)(name: c.Expr[String])(args: c.Expr[Any]*) : c.Expr[Any] = {
import c.universe._
val nameStr = name match { case c.Expr(Literal(Constant(s: String))) => s }
if (nameStr != "sync")
c.Expr[Any](q"""{
val res = ${c.prefix}.t.${newTermName(nameStr)}(..$args)
${c.prefix}.t.sync
res
}""")
else
c.Expr[Any](q"""${c.prefix}.t.sync""")
}
import scala.language.dynamics
class SyncWrapper[T <: { def sync(): Unit }](val t: T) extends Dynamic {
def applyDynamic(name: String)(args: Any*): Any = macro applyDynamicImplementation
}
You'll have to use a compiler plugin for quasiquotes. If you want to call sync before method - just switch val res = ... and ${c.prefix}.t.sync lines.
Usage:
class TestWithSync {
def test(a: String, b: String) = {println("test"); a + b}
def test2(s: String) = {println("test2"); s}
def sync() = println("sync")
}
val w = new SyncWrapper(new TestWithSync)
scala> w.test("a", "b")
test
sync
res0: String = ab
scala> w.test2("s")
test2
sync
res1: String = s
scala> w.invalidTest("a", "b")
<console>:2: error: value invalidTest is not a member of TestWithSync
w.invalidTest("a", "b")
^
You could do it with bytecode rewriting, or with macro annotations. Both would be quite complicated. Some things to consider:
Do you also want this to happen to inherited methods?
If synch calls any other methods of this class, you will get an infinite loop.
Implicit definitions are those that the compiler is allowed to insert into a program in order to fix any of its type errors. For example, if x + y does not type check, then the compiler might change it to convert(x) + y, where convert is some available implicit conversion. If convert changes x into something that has a + method, then this change might fix a program so that it type checks and runs correctly. If convert really is just a simple conversion function, then leaving it out of the source code can be a clarification.
Basically implicit is used for conversion implicitly so i tried it using an example i think it will help you:
scala> class c{
| implicit def synch(x: String)=x.toInt+20
| def f1(s: String):Int=s
| }
what am i doing is :
i am implicitely conversing String to int and adding 20 to that number so for that i defined one method that is synch by using keyword implicit that will take string as an argument and after that convert value to int and adding 20 to it.
in next method if arugment is string and it return type is Int so it will implicitely call that synch method
scala> val aty=new c
aty: c = c#1f4da09
scala> aty.f1("50")
res10: Int = 70
I heard that with Dynamic it is somehow possible to do dynamic typing in Scala. But I can't imagine how that might look like or how it works.
I found out that one can inherit from trait Dynamic
class DynImpl extends Dynamic
The API says that one can use it like this:
foo.method("blah") ~~> foo.applyDynamic("method")("blah")
But when I try it out it doesn't work:
scala> (new DynImpl).method("blah")
<console>:17: error: value applyDynamic is not a member of DynImpl
error after rewriting to new DynImpl().<applyDynamic: error>("method")
possible cause: maybe a wrong Dynamic method signature?
(new DynImpl).method("blah")
^
This is completely logical, because after looking to the sources, it turned out that this trait is completely empty. There is no method applyDynamic defined and I can't imagine how to implement it by myself.
Can someone show me what I need to do to make it to work?
Scalas type Dynamic allows you to call methods on objects that don't exist or in other words it is a replica of "method missing" in dynamic languages.
It is correct, scala.Dynamic doesn't have any members, it is just a marker interface - the concrete implementation is filled-in by the compiler. As for Scalas String Interpolation feature there are well defined rules describing the generated implementation. In fact, one can implement four different methods:
selectDynamic - allows to write field accessors: foo.bar
updateDynamic - allows to write field updates: foo.bar = 0
applyDynamic - allows to call methods with arguments: foo.bar(0)
applyDynamicNamed - allows to call methods with named arguments: foo.bar(f = 0)
To use one of these methods it is enough to write a class that extends Dynamic and to implement the methods there:
class DynImpl extends Dynamic {
// method implementations here
}
Furthermore one need to add a
import scala.language.dynamics
or set the compiler option -language:dynamics because the feature is hidden by default.
selectDynamic
selectDynamic is the easiest one to implement. The compiler translates a call of foo.bar to foo.selectDynamic("bar"), thus it is required that this method has an argument list expecting a String:
class DynImpl extends Dynamic {
def selectDynamic(name: String) = name
}
scala> val d = new DynImpl
d: DynImpl = DynImpl#6040af64
scala> d.foo
res37: String = foo
scala> d.bar
res38: String = bar
scala> d.selectDynamic("foo")
res54: String = foo
As one can see, it is also possible to call the dynamic methods explicitly.
updateDynamic
Because updateDynamic is used to update a value this method needs to return Unit. Furthermore, the name of the field to update and its value are passed to different argument lists by the compiler:
class DynImpl extends Dynamic {
var map = Map.empty[String, Any]
def selectDynamic(name: String) =
map get name getOrElse sys.error("method not found")
def updateDynamic(name: String)(value: Any) {
map += name -> value
}
}
scala> val d = new DynImpl
d: DynImpl = DynImpl#7711a38f
scala> d.foo
java.lang.RuntimeException: method not found
scala> d.foo = 10
d.foo: Any = 10
scala> d.foo
res56: Any = 10
The code works as expected - it is possible to add methods at runtime to the code. On the other side, the code isn't typesafe anymore and if a method is called that doesn't exist this must be handled at runtime as well. In addition this code is not as useful as in dynamic languages because it is not possible to create the methods that should be called at runtime. This means that we can't do something like
val name = "foo"
d.$name
where d.$name would be transformed to d.foo at runtime. But this is not that bad because even in dynamic languages this is a dangerous feature.
Another thing to note here, is that updateDynamic needs to be implemented together with selectDynamic. If we don't do this we will get a compile error - this rule is similar to the implementation of a Setter, which only works if there is a Getter with the same name.
applyDynamic
The ability to call methods with arguments is provided by applyDynamic:
class DynImpl extends Dynamic {
def applyDynamic(name: String)(args: Any*) =
s"method '$name' called with arguments ${args.mkString("'", "', '", "'")}"
}
scala> val d = new DynImpl
d: DynImpl = DynImpl#766bd19d
scala> d.ints(1, 2, 3)
res68: String = method 'ints' called with arguments '1', '2', '3'
scala> d.foo()
res69: String = method 'foo' called with arguments ''
scala> d.foo
<console>:19: error: value selectDynamic is not a member of DynImpl
The name of the method and its arguments again are separated to different parameter lists. We can call arbitrary methods with an arbitrary number of arguments if we want but if we want to call a method without any parentheses we need to implement selectDynamic.
Hint: It is also possible to use apply-syntax with applyDynamic:
scala> d(5)
res1: String = method 'apply' called with arguments '5'
applyDynamicNamed
The last available method allows us to name our arguments if we want:
class DynImpl extends Dynamic {
def applyDynamicNamed(name: String)(args: (String, Any)*) =
s"method '$name' called with arguments ${args.mkString("'", "', '", "'")}"
}
scala> val d = new DynImpl
d: DynImpl = DynImpl#123810d1
scala> d.ints(i1 = 1, i2 = 2, 3)
res73: String = method 'ints' called with arguments '(i1,1)', '(i2,2)', '(,3)'
The difference in the method signature is that applyDynamicNamed expects tuples of the form (String, A) where A is an arbitrary type.
All of the above methods have in common that their parameters can be parameterized:
class DynImpl extends Dynamic {
import reflect.runtime.universe._
def applyDynamic[A : TypeTag](name: String)(args: A*): A = name match {
case "sum" if typeOf[A] =:= typeOf[Int] =>
args.asInstanceOf[Seq[Int]].sum.asInstanceOf[A]
case "concat" if typeOf[A] =:= typeOf[String] =>
args.mkString.asInstanceOf[A]
}
}
scala> val d = new DynImpl
d: DynImpl = DynImpl#5d98e533
scala> d.sum(1, 2, 3)
res0: Int = 6
scala> d.concat("a", "b", "c")
res1: String = abc
Luckily, it is also possible to add implicit arguments - if we add a TypeTag context bound we can easily check the types of the arguments. And the best thing is that even the return type is correct - even though we had to add some casts.
But Scala would not be Scala when there is no way to find a way around such flaws. In our case we can use type classes to avoid the casts:
object DynTypes {
sealed abstract class DynType[A] {
def exec(as: A*): A
}
implicit object SumType extends DynType[Int] {
def exec(as: Int*): Int = as.sum
}
implicit object ConcatType extends DynType[String] {
def exec(as: String*): String = as.mkString
}
}
class DynImpl extends Dynamic {
import reflect.runtime.universe._
import DynTypes._
def applyDynamic[A : TypeTag : DynType](name: String)(args: A*): A = name match {
case "sum" if typeOf[A] =:= typeOf[Int] =>
implicitly[DynType[A]].exec(args: _*)
case "concat" if typeOf[A] =:= typeOf[String] =>
implicitly[DynType[A]].exec(args: _*)
}
}
While the implementation doesn't look that nice, its power can't be questioned:
scala> val d = new DynImpl
d: DynImpl = DynImpl#24a519a2
scala> d.sum(1, 2, 3)
res89: Int = 6
scala> d.concat("a", "b", "c")
res90: String = abc
At the top of all, it is also possible to combine Dynamic with macros:
class DynImpl extends Dynamic {
import language.experimental.macros
def applyDynamic[A](name: String)(args: A*): A = macro DynImpl.applyDynamic[A]
}
object DynImpl {
import reflect.macros.Context
import DynTypes._
def applyDynamic[A : c.WeakTypeTag](c: Context)(name: c.Expr[String])(args: c.Expr[A]*) = {
import c.universe._
val Literal(Constant(defName: String)) = name.tree
val res = defName match {
case "sum" if weakTypeOf[A] =:= weakTypeOf[Int] =>
val seq = args map(_.tree) map { case Literal(Constant(c: Int)) => c }
implicitly[DynType[Int]].exec(seq: _*)
case "concat" if weakTypeOf[A] =:= weakTypeOf[String] =>
val seq = args map(_.tree) map { case Literal(Constant(c: String)) => c }
implicitly[DynType[String]].exec(seq: _*)
case _ =>
val seq = args map(_.tree) map { case Literal(Constant(c)) => c }
c.abort(c.enclosingPosition, s"method '$defName' with args ${seq.mkString("'", "', '", "'")} doesn't exist")
}
c.Expr(Literal(Constant(res)))
}
}
scala> val d = new DynImpl
d: DynImpl = DynImpl#c487600
scala> d.sum(1, 2, 3)
res0: Int = 6
scala> d.concat("a", "b", "c")
res1: String = abc
scala> d.noexist("a", "b", "c")
<console>:11: error: method 'noexist' with args 'a', 'b', 'c' doesn't exist
d.noexist("a", "b", "c")
^
Macros give us back all compile time guarantees and while it is not that useful in the above case, maybe it can be very useful for some Scala DSLs.
If you want to get even more information about Dynamic there are some more resources:
The official SIP proposal that introduced Dynamic into Scala
Practical uses of a Dynamic type in Scala - another question on SO (but very outdated)
kiritsuku's answer is better. This is to show a practical TL;DR use case.
Dynamics can be used to dynamically construct an object with the builder pattern.
import scala.language.dynamics
case class DynImpl(
inputParams: Map[String, List[String]] = Map.empty[String, List[String]]
) extends Dynamic {
def applyDynamic(name: String)(args: String*): DynImpl = {
copy(inputParams = inputParams ++ Map(name -> args.toList))
}
}
val d1 = DynImpl().whatever("aaa", "bbb").cool("ccc")
println(d1.inputParams) // Map(whatever -> List(aaa, bbb), cool -> List(ccc))
val d2 = DynImpl().whatever("aaa", "bbb").fun("haha")
println(d2.inputParams) // Map(whatever -> List(aaa, bbb), fun -> List(haha))
As far as I can tell, Scala has definitions for the Enumeration Value class for Value(Int), Value(String), and Value(Int, String).
Does anyone know of an example for creating a new Value subclass to support a different constructor?
For example, If I want to create an Enumeration with Value(Int, String, String) objects, how would I do it? I would like all of the other benefits of using the Enumeration class.
Thanks.
The Enumeration values are instance of the Val class. This class can be extended and a factory method can be added.
object My extends Enumeration {
val A = Value("name", "x")
val B = Value("other", "y")
class MyVal(name: String, val x : String) extends Val(nextId, name)
protected final def Value(name: String, x : String): MyVal = new MyVal(name, x)
}
scala> My.B.id
res0: Int = 1
scala> My.B.x
res1: String = y
Actually in Scala Enumeration has a much simpler meaning than in Java. For your purpose you don't have to subclass Enumeration nor its Value in any way, you just need to instantiate your own type in its companion object as a val. This way you'll get the familiar access model of val value:MyEnum = MyEnum.Value as you had in Java which is not possible in the example provided by Thomas Jung. There you'll have def value:My.MyVal = MyEnum.Value which is kinda confusing as it seems to me besides all the hackiness of the solution. Here's an example of what I propose:
class MyEnum(myParam:String)
object MyEnum {
val Value1 = new MyEnum("any parameters you want")
val Value2 = new MyEnum("")
object Value3 extends MyEnum("A different approach to instantialization which also lets you extend the type in place")
}
Here you'll find a more complicated example: Scala Best Practices: Trait Inheritance vs Enumeration
I would prefer doing it by extending the Enumeration.Val class.
For your requirement, I would post a sample below:
object FileType extends Enumeration {
val csv = Val(1,"csv", ",")
val tsv = Val(2,"tsv", "\t")
protected case class Val(num: Int, fileType: String, delimiter: String) extends super.Val
implicit def valueToFileType(x: Value): Val = x.asInstanceOf[Val]
}
Accessing values is as below:
scala> FileType.csv
res0: FileType.Val = csv
scala> FileType.csv.delimiter
res29: String = ,
Here is another simpler approach:
scala> :paste
// Entering paste mode (ctrl-D to finish)
object Colors extends Enumeration {
sealed case class Color private[Colors](hexCode: String, name: String) extends Val(name)
val Black = Color("#000000", "black")
val White = Color("#FFFFFF", "white")
}
// Exiting paste mode, now interpreting.
defined object Colors
scala> Colors.Black.hexCode
res0: String = #000000
scala> Colors.Black.name
res1: String = black
scala> Colors.values
res2: Colors.ValueSet = Colors.ValueSet(black, white)
scala>