-1

I am fairly new to Scala and am having a build error which states Public method must have explicit type. Just wanted to know if anyone has come across this kind of error and if so how to fix it?

def pk = primaryKey("passive_prompts_primary_key", (uuid, promptType, trigger))

Is where the error is forming

My best guess is to add the return type in but I am not sure how to do that

1 Answers1

4

You should specify the return type because the method pk is public (instead of ???)

def pk: ??? = primaryKey("passive_prompts_primary_key", (uuid, promptType, trigger))

It's hard to say what exactly to write here instead of ??? because only you can know what type primaryKey(...) returns.

Normally Public method must have explicit type should be a warning, not error. Probably you have switched on in build.sbt something like -Xfatal-warnings (Scala 2.12) or -Werror (Scala 2.13). One of options is to switch it off but probably this is not recommended because it's a useful option.

Now about how you can find yourself the type of primaryKey(...) (in order to know what to write instead of ???).

  • You can look at the definition of def primaryKey....

  • Alternatively you can start the REPL with sbt console and write the right hand side of pk, something like

scala> import SomeObject._ // where primaryKey, uuid, promptType, trigger are defined

scala> primaryKey("passive_prompts_primary_key", (uuid, promptType, trigger))

The REPL then write the value and type of pk.

enter image description here

  • Or you can use functionality of IDE. I'm pressing Alt+Enter in ItelliJ Idea and choose "Add type annotation to definition".

enter image description here

But Idea can sometimes guess types incorrectly.

  • Or you can use self-defined getType in the project
// add to build.sbt: libraryDependencies += scalaOrganization.value % "scala-reflect" % scalaVersion.value
import scala.reflect.runtime.universe.{TypeTag, Type, typeOf}

def getType[T: TypeTag](t: T): Type = typeOf[T]

println(getType(
  primaryKey("passive_prompts_primary_key", (uuid, promptType, trigger))
))
  • Also there is Scalafix rule that adds explicit return types

https://scalacenter.github.io/scalafix/docs/rules/ExplicitResultTypes.html

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • https://stackoverflow.com/questions/7858588/how-do-i-view-the-type-of-a-scala-expression-in-intellij https://stackoverflow.com/questions/19386964/i-want-to-get-the-type-of-a-variable-at-runtime – Dmytro Mitin Dec 09 '22 at 02:24