Scala Option Return Type

I am new to the Scala programming world, but love it. I recently started porting my research application to Scala, and one of the things I'm still struggling with is the return keyword. For example, in the code below

def readDocument(dbobj:MongoDBObject) = Option[ContainerMetaData] { for(a <- dbobj.getAs[String]("classname"); b <- dbobj.getAs[Long]("id"); c <- dbobj.getAs[Long]("version"); d <- dbobj.getAs[String]("description"); e <- dbobj.getAs[String]("name"); f <- dbobj.getAs[String]("tag"); g <- dbobj.getAs[Int]("containertype"); h <- dbobj.getAs[Date]("createddate") ) { val ctype = ContainerType(g) val jodadt = new DateTime(h) val data = new ContainerMetaData(a,b,c,d,e,f,ctype,jodadt) Some(data) } None } 

In the above code, I get an error:

 type mismatch; found : None.type required: om.domain.ContainerMetaData 

So, if I delete the explicit type of the return code, then the code works, but without the explicit keyword return I can not complete my code with Some(data) .

 def readDocument(dbobj:MongoDBObject)= { for(a <- dbobj.getAs[String]("classname"); b <- dbobj.getAs[Long]("id"); c <- dbobj.getAs[Long]("version"); d <- dbobj.getAs[String]("description"); e <- dbobj.getAs[String]("name"); f <- dbobj.getAs[String]("tag"); g <- dbobj.getAs[Int]("containertype"); h <- dbobj.getAs[Date]("createddate") ) { val ctype = ContainerType(g) val jodadt = new DateTime(h) val data = new ContainerMetaData(a,b,c,d,e,f,ctype,jodadt) Some(data) } None } 

And if you add the return keyword, the compiler complains

 method `readDocument` has return statement; needs result tye 

A little more additional information, this is a trait that I spread

 trait MongoDAOSerializer[T] { def createDocument(content:T) : DBObject def readDocument(db:MongoDBObject) : Option[T] } 
+4
source share
1 answer

The problem is that you are missing the yield keyword for understanding. And also None at the end is not necessary, because for understanding there will be None if one of the values ​​is absent, as well as the explicit creation of Some in the understanding is not required, since it will create an Option anyway. Your code will look like this (not verified)

 def readDocument(dbobj: MongoDBObject): Option[ContainerMetaData] = { for { a <- dbobj.getAs[String]("classname") b <- dbobj.getAs[Long]("id") c <- dbobj.getAs[Long]("version") d <- dbobj.getAs[String]("description") e <- dbobj.getAs[String]("name") f <- dbobj.getAs[String]("tag") g <- dbobj.getAs[Int]("containertype") h <- dbobj.getAs[Date]("createddate") } yield { val ctype = ContainerType(g) val jodadt = new DateTime(h) new ContainerMetaData(a,b,c,d,e,f,ctype,jodadt) } } 
+8
source

All Articles