scala - Can destructuring cause bugs in future? -


initialy have code like

class person(firstname: string, lastname: string)  val (firstname, lastname) = person 

somebody swaps fields

class person(lastname: string, firstname: string)  val (firstname, lastname) = person 

compiler happy!

the compiler has no way know swapped order of fields because analysis doesn't argument name. long typer type checks, fine. can additional level of types:

case class firstname(name: string) case class lastname(name: string)  class person(firstname: firstname, lastname: lastname) 

now swapping types cause compile time error.

if don't want additional overhead of allocationing additional objects, shapeless tagged types:

import shapeless.tag.@@  trait firstnametag trait lastnametag  type firstname = string @@ firstnametag type lastname = string @@ lastnametag  case class person(fn: firstname, ln: lastname) 

and now:

import shapeless.tag  val firstname: firstname = tag[firstnametag][string]("yuv") val lastname: lastname = tag[lastname][string]("itz")  val person = person(firstname, lastname) 

or @ren points out use value classes:

case class firstname(name: string) extends anyval case class lastname(name: string) extends anyval 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -