Pregunta

What I need:

trait Base {
  import scala.math.{Pi=>mPi, cos=>msoc, sin=>msin}
  static val Pi : Float = mPi.toFloat
  static def cos(phi : Float) : Float = mcos(phi).toFloat
  static def sin(phi : Float) : Float = msin(phi).toFloat
  // ...
  // some useful functions
}
// children use float defined pi, cos and sin without additional boilerplate
class Child1 extends Base
// ...
class Child2 extends Base

That obviously would not work. What I tried

trait Base {
  import Base._
  // some useful functions
}
object Base {
  // utility functions
  import scala.math.{Pi=>mPi, cos=>mcos, sin=>msin}
  val Pi : Float = mPi.toFloat
  def cos(phi : Float) : Float = mcos(phi).toFloat
  def sin(phi : Float) : Float = msin(phi).toFloat
}
class Child1 extends Base {
  // use sin and cos inside
}

And the compiler gives errors in Child1 that it does nothing about functions sin and cos.

How can I define a static members in a base class that would be inherited by its descendants?

¿Fue útil?

Solución

Why are you thinking in terms of static? All you need to do is create a method with no argument list that returns the Float forms of your constants.

For better or worse, as you've discovered, imports in a class or trait scope a not inherited.

package rrs.scribble

trait   FloatMath
{
  import scala.math.{Pi => mPi, cos => mcos, sin => msin}

  def Pi: Float = mPi.toFloat
  def cos(phi: Float): Float = mcos(phi).toFloat
  def sin(phi: Float): Float = msin(phi).toFloat
}

object  FM1
extends FloatMath
{
  val twoPi = 2.0f * Pi
}

In the REPL:

scala> import rrs.scribble.FM1._
import rrs.scribble.FM1._

scala> twoPi
res0: Float = 6.2831855

scala> cos(twoPi)
res1: Float = 1.0

As you see, the static types of Pi, twoPi, cos, etc. are all Float, not Double.

Otros consejos

How about choosing either mixing in a trait or importing members from an object?

And I think the latter is better.

trait MathUtils { 
  def cos(phi : Float) : Float = ...
}
class Child1 extends MathUtils { cos(1.0F) }

or

object MathUtils { 
  def cos(phi : Float) : Float = ...
}
class Child1 { 
  import MathUtils._
  cos(1.0F)
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top