Jake
Jake

Reputation: 4670

Scala: Case class with generic function argument

I have the following case class.

case class CustomAttributeInfo[T,Y](
          attribute:MyAttribute[_],
          fieldName:String, 
          valueParser:T => Y){}

The case class takes three values.

The last argument is a function that will parse an input of any type and return the part of the input we wish to keep.

(Imagine, for just one example, I pass in a jsonstring, convert to json object, and extract an Int).

The companion object will supply a range of functions that we can pass to the case class. The one shown here, simply takes the input as a string and returns it as a string (the most simple possible example).

object CustomAttributeInfo {

  val simpleString = (s:String) => s
}

I create the case class as follows:

CustomAttributeInfo(MyAttribute(var1, var2), name, CustomAttributeInfo.simpleString)

Later, I call the function 'valueParser'

customAttributeInfo.valueParser(k)

Compilation error

Error:(366, 69) type mismatch; found : k.type (with underlying type String) required: _$13 case Some(info) => Some((info.attribute, info.valueParser(k)))

I am not a generics expert (obviously). I have done some reading, but I have not seen a discussion about a case like this. Any advice and explanation would be most welcome

Upvotes: 0

Views: 540

Answers (2)

Jake
Jake

Reputation: 4670

@Dmytro was right that a simple example compiled. In my actual codebase code, however, we needed to be specific about the type.

This worked:

object CustomAttributeInfo {

  type T = Any

  val simpleString = (s:T) => s.toString
}

Upvotes: 0

Dmytro Mitin
Dmytro Mitin

Reputation: 51703

You haven't provide enough information to answer your question.

The following code compiles.

If you still have compile error provide MCVE.

  case class MyAttribute[_](var1: Any, var2: Any)

  case class CustomAttributeInfo[T,Y](attribute:MyAttribute[_], fieldName:String, valueParser:T => Y) {}

  object CustomAttributeInfo {

    val simpleString = (s:String) => s
  }

  val var1: Any = ???
  val var2: Any = ???
  val name: String = ???
  val customAttributeInfo = CustomAttributeInfo(MyAttribute(var1, var2), name, CustomAttributeInfo.simpleString)

  val k = "abc"
  customAttributeInfo.valueParser(k)

Upvotes: 3

Related Questions