例如,我希望将此方法设置为将jDName
设置为“John Doe”并将jDAge
设置为32:
case class Person(name : String, surname : String, age : Int)
val johnDoe = Person("John", "Doe", 32)
val jDName : String = johnDoe
val jDAge : Int = johnDoe
我可以在Person
类中编写函数来提供对String,Int和其他(自定义)类型的隐式转换吗?另一件事是显式的强制转换操作 - 也很有趣,但我不确切地知道如何在Scala中编写这个例子。
答案 0 :(得分:8)
这会有用吗?
object Person {
implicit def pToString(p: Person) = p.name + " " + p.surname + ", age " + p.age
implicit def pToInt(p: Person) = p.age
}
import Person._
答案 1 :(得分:4)
当然,把它们放在伴侣物中。
scala> case class Person(name : String, surname : String, age : Int); object Person {
| implicit def pToString(p: Person) = p.name + " " + p.surname + ", age " + p.age
| implicit def pToInt(p: Person) = p.age
| }
defined class Person
defined module Person
scala> val johnDoe = Person("John", "Doe", 32)
johnDoe: Person = Person(John,Doe,32)
scala> val jDName : String = johnDoe
jDName: String = John Doe, age 32
scala> val jDAge : Int = johnDoe
jDAge: Int = 32