Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created July 9, 2011 09:58
Show Gist options
  • Save xuwei-k/1073474 to your computer and use it in GitHub Desktop.
Save xuwei-k/1073474 to your computer and use it in GitHub Desktop.
Type Parameter NotNothing Pattern ?
scala> import com.mongodb.casbah.Imports._
import com.mongodb.casbah.Imports._
// MongoDBObjectつくる
scala> val obj = MongoDBObject("a" -> 1)
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
obj: com.mongodb.casbah.commons.Imports.DBObject = { "a" : 1}
// 型引数を明示する、正しい使い方
scala> obj.getAs[Int]("a")
res0: Option[Int] = Some(1)
// 型引数を明示しない、間違った使い方すると実行時例外になってしまう
scala> obj.getAs("a")
java.lang.IllegalArgumentException: requirement failed: Type inference failed; getAs[A]() requires an explicit type argument (e.g. dbObject.getAs[<ReturnType>]("somegetAKey") ) to function correctly.
at scala.Predef$.require(Predef.scala:157)
at com.mongodb.casbah.commons.MongoDBObject$class.getAs(MongoDBObject.scala:96)
at com.mongodb.casbah.commons.Implicits$$anon$1.getAs(Implicits.scala:55)
at .<init>(<console>:12)
at .<clinit>(<console>)
at .<init>(<console>:11)
at .<clinit>(<console>)
at $export(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:592)
at scala.tools.nsc.interpreter.IMain$Request$$anonfun$10.apply(IMain.scala:828)
at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
at scala.tools.nsc.io.package$$anon$2.run(package.scala:31)
at java.lang.Thread.run(Thread.java:636)
// コンパイルエラーにするために、ダミーの implicit val を定義
scala> implicit val amb1,amb2 = manifest[Nothing]
amb1: Manifest[Nothing] = Nothing
amb2: Manifest[Nothing] = Nothing
// 型引数明示しないで渡すと、コンパイルエラーにできるじゃん !!!
scala> obj.getAs("a")
<console>:14: error: ambiguous implicit values:
both value amb1 in object $iw of type => Manifest[Nothing]
and value amb2 in object $iw of type => Manifest[Nothing]
match expected type scala.reflect.Manifest[A]
obj.getAs("a")
^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment