Scala type classes

I have a custom type defined like this:

type MyType = (String, String)

      

When I use this type I always need to traverse the tuple numbering which I hate. I can of course do the following and unpack what is inside like below:

val (str1, str2) = myType

      

Can I create a companion object for this type and have two methods that give me the first and second elements in the tuple? I would rather do the following:

myType.str1 will give me the first element and myType.str2 will give me the second element.

+3


source to share


2 answers


How about this:



scala> type MyType = (String, String)
defined type alias MyType

scala> implicit class MyPair(val t: MyType) extends AnyVal {
     |   def str1 = t._1
     |   def str2 = t._2
     | }
defined class MyPair

scala> val mt: MyType = ("Hello", "World")
mt: MyType = (Hello,World)

scala> mt.str1
res0: String = Hello

scala> mt.str2
res1: String = World

      

+3


source


Can I create a companion object for this type and have two methods that give me the first and second elements in the tuple?

Of course, this is what the case class does.

How about just



case class MyType(str1: String, str2: String)

      

without resorting to awkward type aliases?

+13


source







All Articles