2016-02-02 111 views
2

我不知道爲什麼下面的代碼無法編譯,這是錯誤消息:沒有類型參數的方法flatMap

Error:(29, 7) no type parameters for method flatMap: (f: String => Option[B])Option[B] exist so that it can be applied to arguments (String => Some[Class[?0]] forSome { type ?0 <: org.apache.hadoop.io.compress.CompressionCodec })
--- because ---
argument expression's type is not compatible with formal parameter type; found : String => Some[Class[?0]] forSome { type ?0 <: org.apache.hadoop.io.compress.CompressionCodec }
required: String => Option[?B]
a.flatMap(codecClassName => {
^

和代碼

def f(a: Option[String]): Unit = { 
    a.flatMap(codecClassName => { 
     val codecFactory = new CompressionCodecFactory(new Configuration()) 
     val codecClass = codecFactory.getCodecClassByName(codecClassName) 
     if (codecClass == null) { 
     throw new RuntimeException("Unknown or not supported codec:" + codecClassName) 
     } 
     Some(codecClass) 
    }) 
    } 

回答

0

這似乎是有關getClass和classOf沒有返回完全相同的事實。有關更多詳情,請參閱Scala equivalent of Java java.lang.Class<T> Object

尋找解決辦法我遇到了Scala Getting class type from string representation

因此,如何:

val codecClass = Manifest.classType(codecFactory.getCodecClassByName(codecClassName)) 
+0

謝謝,它的工作原理,但我還是不明白,爲什麼我不能使用的getClass,即使它是從classOf不同,但我並沒有將它們混合。 – zjffdu

相關問題