![]() ![]() If you instantiate a Usability score with the "durability" column, the compiler won't know the different, but an attentive reviewer would quickly spot the confusion. This makes a bit more code to write, but it explicitly marks the semantic of the Ints that you are passing in making the code easier to understand and the scala compiler will now complain when you create Scoring with the scores in the wrong order. ![]() The simple solution would be to create wrapper classes for each type of score: case class Design(val score: Int) extends AnyValĬase class Usability(val score: Int) extends AnyValĬase class Durability(val score: Int) extends AnyValĬase class Scoring(user: User, product: Product, design: Design, usability: Usability, durability: Durability) ![]() however, the second error, inverting the durability score and the usability score will not be spotted by the compiler and even a code reviewer would have to be very concentrated to spot such a trivial error.the scala compiler performing type check would straightaway flag the inverted product/user parameters as a compilation error: type mismatch found : Product required: User,.If you are like me, you will have to go check in the documentation to know in what order to set the parameters.įor instance, you might write something like this, to create an instance with Anorm from a database query: def parseProduct(row: Row): Product = …ĭef parseScoring(row: Row): Scoring = Scoring( The issue here is that the Scoring constructor is simple, but not very safe. You will probably end up creating such objects in different parts of your code, from raw Ints coming from diverse sources, such as a REST request, or from parsing a line from your database. Now, you can create Scoring instances in your code Scoring(u1, p1, 10, 15, 20). You could represent a score with a simple object: case class User(id: Long)Ĭase class Scoring(user: User, product: Product, design: Int, usability: Int, durability: Int) Each product can be scored along different dimensions: design, usability, durability. Imagine that you are trying to get users to score products. This will help the compiler can automatically detect more errors and a code reviewer to understand better what's going on. I am giving a simple example here, it's a bit naive and there would be other ways to implement it, but I hope you will still understand the overarching concept: being able to annotate the meaning of basic type parameters (and variables) such as Int, List, etc. This was inspired by Eric Torreborre's post that gives a very good use case for what I am going to show, but I wanted to share another one. Here is another "fun" dive in the complex type system of Scala. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |