简体   繁体   中英

Accessing members of a Scala object

I have called a Spark RDD's first() methods, and it had returned an object that looks as follows:

session: Any = (SessionKey{m_sessionId=91249793986979128, m_publisherId=196, m_sessionStartTimeTimeSlice=1439164800000},Session{m_pageViewsIds=[ViewId [m_viewId=1439166315327]]})

How can I access the member variables of this object?

When I run session.getClass, the result is:

Class[_] = class scala.Tuple2

Yet, when I try to access the members with _1 and _2, I get the following message:

error: value _1 is not a member of Any 
session._1

When I try to cast it by calling session.asInstanceOf[(SessionKey, Session)]._1, I get:

error: not found: type SessionKey    
session.asInstanceOf[(SessionKey, Session)]._1 
error: not found: type Session 
session.asInstanceOf[(SessionKey, Session)]._1

If you always expect session it to be the same type, then make explicit cast to that type:

val sessionWithType = session.asInstanceOf[(SessionKey, Session)]
sessionWithType._1

If you are not sure about the type, try matching:

val sessionAsOption = session match {
  case s:(SessionKey, Session) => Some(s) 
  case _ => None 
}

sessionAsOption.foreach {
  session => session._1
}

It the later example you'll get Some() when session matched the expected type and None otherwise.

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