Home > Net >  Use enum type in function definition
Use enum type in function definition

Time:12-21

I am struggling using a enum type in the function definition of Scala code.

What I did is:

object LogType extends Enumeration {
    type LogType = Value
    val TRACE = Value(100)
    val DEBUG = Value(90)
    val INFO = Value(80)
    val WARN = Value(70)
    val ERROR = Value(60)
    val FATAL = Value(50)
}

def logMessage(mtype: LogType, message: String): Unit = {

<console>:186: error: not found: type LogType
       def logMessage(mtype: LogType, message: String): Unit = {tring): Unit = {

It seems that the type is not found, although declared before the function definition.

Then the next question is how to use it within the function, in particular the syntax of this here (when to use value, etc.) is very confusing: scala def

logPerf(message: String, startTimeMillisec : Long, endTimeMillisec : Long): Unit = 
{    
val formatedmessage = String.format(message, (endTimeMillisec- startTimeMillisec) / 1000   " ms")   
logMessage(LogType.TRACE, formatedmessage) 

}   

def logMessage(mtype: LogType.Value, message: String): Unit = {  

mtype match 
{     
case LogType.TRACE  => if( AssignedLogLevel <= mtype ){ log.trace( message ) 
}

https://i.postimg.cc/MHg6hNnv/log.pnglogLog

What would be correct in that case?

CodePudding user response:

Here is a simple example of using a trait, as mentioned in the comments:

trait LogType {
  def level: Int
}

abstract class LogLevel(val level: Int) extends LogType

object TRACE extends LogLevel(100)
object DEBUG extends LogLevel(90)
object INFO extends LogLevel(80)
object WARN extends LogLevel(70)
object ERROR extends LogLevel(60)
object FATAL extends LogLevel(50)

def logMessage(mtype: LogType, message: String): Unit =
  if (mtype.level <= AssignedLogLevel) {
   log.trace(message)
  }
  • Related