I'm trying to make a EnumListField in Lift/Record/Squeryl, similar to MappedEnumList in LiftMapper. The storage type should be Long/BIGINT. I understand that if I define:
def classOfPersistentField = classOf[Long]
Then Squeryl will know it should create a BIGINT column. And I know it uses setFromAny() to set the value, passing in the Long. The one piece I don't get is:
How will it read the field's value? If it uses valueBox, it will get a Seq[Enum#Value], and it won't know how to turn that into a Long.
How do I tell Squeryl to convert my Seq[Enum#Value] to a Long, or define a "getter" that returns a Long, and that doesn't conflict with the "normal" getter(s)?
you are implementing your validation logic incorrectly. The correct way to validate a Record field is to override
def validations: List[ValidationFunction]
where ValidationFunction is a type alias
type ValidationFunction = ValueType => List[FieldError]
and in your case ValueType == String.
The next issue is your Domain trait. Because your call to validate is inlined into the class definition, it will be called when your field is constructed.
Related
Let's say I have the below case class that translates directly a db table and where the id will be generated randomly on the creation of a new row.
case class Test(id: UUID, name: String)
Looking at the tests right now, I need to retrieve a row from Test and compare it with
val test1 = (...., "testName")
however I don't have the first parameter since it's created randomly and I would like to ignore it somehow...
I tried doing
test1 = (_, "testName")
but it's not valid.
Is there any way where I can ignore in Scala a case class parameter ?
Thanks!
Assuming we have
case class Test(id: UUID, name: String)
Here's a function that tests two instances of Test for equality, ignoring the id field.
def myEquality(a: Test, b: Test): Boolean =
a == b.copy(id=a.id)
We can't explicitly tell Scala to ignore a field, but we can most certainly mock that field to be the correct value. And since these are case classes (i.e. immutable), we can't mess up any other unrelated data structures by doing this simple trick.
To answer the question posed, the answer is no. Case class instances are defined by the values of their fields. They do not have the property of identity like normal classes. So instantiating a case class with a missing parameter is not possible.
How is it possible to create variable of type Any?
And why does isInstanceOf[Int] print true?
I declared x to be Any, not Int.
How does it work? What is happening behind the scenes?
val x = 4: Any // OK
x.isInstanceOf[Int] // true
x.isInstanceOf[String] // false
[EDIT] Maybe to rephrase my question:
How does val x = 4: Any look like in memory?
And once it is stored in memory as Any type, how can I later say that this particular blob of bytes is Int, but not say String?
Does it come along with some kind of information what was the "original" type? Here for example if I typed 4 AND LATER said this is Any type, would it store this original type of 4 as an Int?
Scala language is defined to support the notion of inheritance polymorphism. In other words, if there is some type T which inherits from type U, then any value of type T can be assigned to a variable of type U:
class T extends U
val x: U = new T // compiles
Same thing with Any and Int: in Scala, Int inherits from Any, therefore it is possible to store an integer in an Any variable:
val x: Any = 4 // essentially the same as your example
Also, all of the runtimes Scala runs on know what type of value is actually stored in a variable, regardless of the static type of this variable. This is important for many features of the language, in particular, virtual method overrides, but it also allows you to do manual checks and downcasts, which is what your code does (the checks). In other words, the isInstanceOf method checks the runtime type of a value stored in a variable, not the static type known at the compile time (which would be quite pointless).
case class AlertWindowDto(id: String)
protected val InitialWindowPeriodOneOnPeak = AlertWindowDto(ValidId)
protected val ValidId = "someSite"
I saw these there lines in different different classes. just I put together for understanding.
In general, If i am creating an dummy or some object of Class, then I give some value or null or empty string. What is the need of creating another field ValidId and assign some value and assign that field to final object.
is there any benefit, or anything help in test cases.
could you please help me.
Imagine this:
protected val InitialWindowPeriodOneOnPeak = AlertWindowDto("someSite")
Does it convey the information that "someSite" is a valid id for an alert window?
This is a trivial example, but the general idea is that sometimes breaking down expressions and assigning names to them is great for expressing meaning.
I would also add that the more this naming information is in the types, the better. For instance, here's another way of achieving the same result, without using a variable name.
case class ValidId(value: String) extends AnyVal
case class AlertWindowDto(id: ValidId)
protected val InitialWindowPeriodOneOnPeak = AlertWindowDto(ValidId("someSite"))
Same information, but the "valid id" information is now stored in the type system.
I've just read: http://oldfashionedsoftware.com/2008/08/20/a-post-about-nothing/
As far as I understand, Null is a trait and its only instance is null.
When a method takes a Null argument, then we can only pass it a Null reference or null directly, but not any other reference, even if it is null (nullString: String = null for example).
I just wonder in which cases using this Null trait could be useful.
There is also the Nothing trait for which I don't really see any more examples.
I don't really understand either what is the difference between using Nothing and Unit as a return type, since both doesn't return any result, how to know which one to use when I have a method that performs logging for example?
Do you have usages of Unit / Null / Nothing as something else than a return type?
You only use Nothing if the method never returns (meaning it cannot complete normally by returning, it could throw an exception). Nothing is never instantiated and is there for the benefit of the type system (to quote James Iry: "The reason Scala has a bottom type is tied to its ability to express variance in type parameters."). From the article you linked to:
One other use of Nothing is as a return type for methods that never
return. It makes sense if you think about it. If a method’s return
type is Nothing, and there exists absolutely no instance of Nothing,
then such a method must never return.
Your logging method would return Unit. There is a value Unit so it can actually be returned. From the API docs:
Unit is a subtype of scala.AnyVal. There is only one value of type
Unit, (), and it is not represented by any object in the underlying
runtime system. A method with return type Unit is analogous to a Java
method which is declared void.
The article you quote can be misleading. The Null type is there for compatibility with the Java virtual machine, and Java in particular.
We must consider that Scala:
is completely object oriented: every value is an object
is strongly typed: every value must have a type
needs to handle null references to access, for example, Java libraries and code
thus it becomes necessary to define a type for the null value, which is the Null trait, and has null as its only instance.
There is nothing especially useful in the Null type unless you're the type-system or you're developing on the compiler. In particular I can't see any sensible reason to define a Null type parameter for a method, since you can't pass anything but null
Do you have usages of Unit / Null / Nothing as something else than a
return type?
Unit can be used like this:
def execute(code: => Unit):Unit = {
// do something before
code
// do something after
}
This allows you to pass in an arbitrary block of code to be executed.
Null might be used as a bottom type for any value that is nullable. An example is this:
implicit def zeroNull[B >: Null] =
new Zero[B] { def apply = null }
Nothing is used in the definition of None
object None extends Option[Nothing]
This allows you to assign a None to any type of Option because Nothing 'extends' everything.
val x:Option[String] = None
if you use Nothing, there is no things to do (include print console)
if you do something, use output type Unit
object Run extends App {
//def sayHello(): Nothing = println("hello?")
def sayHello(): Unit = println("hello?")
sayHello()
}
... then how to use Nothing?
trait Option[E]
case class Some[E](value: E) extends Option[E]
case object None extends Option[Nothing]
I've never actually used the Null type, but you use Unit, where you would on java use void. Nothing is a special type, because as Nathan already mentioned, there can be no instance of Nothing. Nothing is a so called bottom-type, which means, that it is a sub-type of any other type. This (and the contravariant type parameter) is why you can prepend any value to Nil - which is a List[Nothing] - and the list will then be of this elements type. None also if of type Option[Nothing]. Every attempt to access the values inside such a container will throw an exception, because that it the only valid way to return from a method of type Nothing.
Nothing is often used implicitly. In the code below,
val b: Boolean =
if (1 > 2) false
else throw new RuntimeException("error")
the else clause is of type Nothing, which is a subclass of Boolean (as well as any other AnyVal). Thus, the whole assignment is valid to the compiler, although the else clause does not really return anything.
In terms of category theory Nothing is an initial object and Unit is a terminal object.
https://en.wikipedia.org/wiki/Initial_and_terminal_objects
Initial objects are also called coterminal or universal, and terminal objects are also called final.
If an object is both initial and terminal, it is called a zero object or null object.
Here's an example of Nothing from scala.predef:
def ??? : Nothing = throw new NotImplementedError
In case you're unfamiliar (and search engines can't search on it) ??? is Scala's placeholder function for anything that hasn't been implemented yet. Just like Kotlin's TODO.
You can use the same trick when creating mock objects: override unused methods with a custom notUsed method. The advantage of not using ??? is that you won't get compile warnings for things you never intend to implement.
Using Scala, in a Play 2.0 project, I am trying to grab data from a config file.
At present I use the following code to extract a String:
val foo = Play.current.configuration.getString("foo")
I had expected to get a String object back, but instead an Option[String] object is returned.
I cannot find any Java docs describing the Option[T] object and calling the toString() returns Some( foo ).
The same happens when using the configuration methods to extract Boolean and Int values from the config - ie, Option[Boolean] and Option[Int] are returned.
Can anyone explain what this Option[T] object is and how I can access the value I want in the form that the application method call implies it will be returned?
In scala, the type Option[T] represents an optional value of the type T. If you are used to Java terms, you could refer to an Option as 'a value that might be null'.
In Play they are used when getting the configuration because the string might not be present - if you would try to read it using Java, it would return null.
To get the config string you can use getOrElse, which lets you provide a default value in case the config string doesn't exist:
val foo = Play.current.configuration.getString("foo").getOrElse("bar")