Conversion

case class

case class Person(name: String)
  def greet(): String = s"Hello, $name"
given fromStringToPerson: Conversion[String, Person] = Person(_)
@main def run =
  println("John".greet())

Scope

The conversion rules are the same as the given rules

  1. imported conversion
  2. current scope
  3. companion object

Exercises

Exercise 1

case class Person(name: String)
  def greet(): String = s"Hello, $name"
  1. Write a conversion function from Person to Int that calculate the length of the name
  2. Put it in a separate object
  3. Use it with an import

Exercise 2

case class User(name: String)
  def login(): String = s"Logged in: $name"
  1. Write a conversion from Person to User
  2. Write a conversion from User to Person
  3. Test both