di recente ho scoperto che si può usare il
Pimp
arricchire la mia biblioteca modello per aggiungere metodi alle compagno oggetti usando .type
:Come si arricchisce un oggetto pacchetto?
object Whatever { }
implicit class WhateverExtensions(val obj: Whatever.type) {
def greet = println("Hi!")
}
Whatever.greet
Purtroppo lo stesso non sembra funzionare per gli oggetti del pacchetto come scala.math
:
implicit class MathExtensions(val obj: scala.math.type) {
def min(x: Money, y: Money): Money = ???
}
ottengo il seguente errore di compilatore:
Error:(153, 47) type mismatch; found : math.type required: AnyRef Note that math extends Any, not AnyRef. Such types can participate in value classes, but instances cannot appear in singleton types or in reference comparisons. implicit class MathExtensions(val obj: scala.math.type) extends AnyVal { ^
È possibile arricchire un oggetto pacchetto?
Non molto nella documentazione a tutti: http://www.scala-lang.org/files/archive/spec/2.11/09-top-level- definitions.html # pacchetto-oggetti. Sembra impossibile ottenere il tipo di quella cosa: 'tipo T = '' math''.type' restituisce "Errore: (5, 12) identificatore stabile richiesto, ma scala trovato. tipo T =' matematica'. genere". –
Vedi anche: http://www.scala-lang.org/docu/files/packageobjects/packageobjects.html –