简体   繁体   中英

Is there a way to access constants of a (java) class by an alias in scala?

I would like to make a short alias for a java class.

Is there a way to import (or make a type alias to) a java class (eg HttpServletResponse ), and access its constant values (eg HttpServletResponse ) using the alias?

Type alias works fine, but I cannot find a way to access the constants of the class.

EDIT:

I'm sorry I asked a wrong question. I knew importing with a short name works.

What I like to do is avoid writing import ...{HttpServletResponse => Response} every file in which MyHttpServlet is mixed-in.

Type aliases in MyHttpServlet makes it possible without importing, but accessing constants is still the issue. (or maybe it's impossible?)

trait MyHttpServlet extends HttpServlet {
  import javax.servlet.http.HttpServletResponse

  // works
  type Response = HttpServletResponse

  // compile error: object creation impossible, since it has 36 unimplemented members.
  //object Response extends HttpServletResponse

  def notAllowed(response: Response): Unit = {
    // works
    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED)

    // I would like to do something like this
    //response.setStatus(Response.SC_METHOD_NOT_ALLOWED)
  }
}

Just rename the import.

import javax.servlet.http.{HttpServletResponse => Response}

response.setStatus(Response.SC_METHOD_NOT_ALLOWED)

Type aliases don't allow static member access because one can't call members on a type in scala, it is only possible on values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM