0

I want to create companion objects for some imported Java types, so that I do not have to use new to allocate them. I want to start with the type Vector3f is imported from com.jme3.math from jMonkeyEngine.

What I tried is:

package com.jme3.math

object Vector3f {
  def apply() = new Vector3f()
  def apply(x:Float, y:Float, z:Float) = new Vector3f(x,y,z)
}

When compiling this, I get errors:

Error:(8, 21) not found: type Vector3f def apply() = new Vector3f()

When I add import com.jme3.math.Vector3f, I get warning which probably explains what I see:

Warning:(3, 22) imported `Vector3f' is permanently hidden by definition of object Vector3f in package math

How can I create a companion object for com.jme3.math.Vector3f or other types imported from Java?

4

1 回答 1

1

That's a naming issue, you can't have both the Java class and Scala companion object with the same name there.

Either you access Java class inside companion object with the fully qualified name new com.jme3.math.Vector3f(...) or you indicate a different local name while importing it.

import com.jme3.math.{ Vector3f => JV3 }

def apply(): JV3 = new JV3()

Extra example (companion object for Java class org.apache.http.HttpClient):

import org.apache.http.client.{ HttpClient ⇒ HC }

object HttpClient {
  def apply(): HC = ???
}

Or...

// No import
object HttpClient {
  def apply(): org.apache.http.client.HttpClient = ???
}
于 2014-09-04T09:48:42.693 回答