Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement scala generic function that takes subtype of parameterized traits and returns it

I don't need any information about type T on runtime so I think ClassTag is useless here.

I just need to return in my function the same type I've taken as an argument.

class MyClass[T] extends A with B[T] with C with D

trait A
trait B[T] {
  def usefulMethod: Unit = println("B")
}
trait C
trait D {
 def usefulMethodToo: Unit = println("D")
}

I've tried to implement my function like this but compiler infers Nothing


def helper[T, A <: B[T] with D](x: A): A = {
  x.usefulMethod
  x.usefulMethodToo
  x
}

helper(new MyClass[Int])

Can it be inferred by compiler somehow?

like image 965
Awethon Avatar asked Jan 18 '26 23:01

Awethon


1 Answers

The problem is that it can't infer T, but in this (maybe oversimplified?) case you don't actually need it:

def helper[A <: B[_] with D](x: A): A = {
  x.usefulMethod
  x.usefulMethodToo
  x
}

This workaround works too:

def helper[T, A <: B[T] with D](x: A with B[T]): A = {
  x.usefulMethod
  x.usefulMethodToo
  x
}
like image 174
Alexey Romanov Avatar answered Jan 20 '26 15:01

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!