logo
down
shadow

Scala. Checking if a Type is Comparable


Scala. Checking if a Type is Comparable

By : Thang Nguyen
Date : November 22 2020, 10:33 AM
I wish this help you I have a simple class which takes a generic type, Eg: , Something like this perhaps?
code :
def foo[T: TypeTag] = typeOf[T] match {
    case t if t <:< typeOf[Comparable[_]] => "Comparable"
    case _ => "Not Comparable"
}


Share : facebook icon twitter icon
Type parameter Bounds [T <: Comparable[_]] in guava's MinMaxPriorityQueue in Scala

Type parameter Bounds [T <: Comparable[_]] in guava's MinMaxPriorityQueue in Scala


By : Sean Zhao
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Trying to create a MinMaxPriorityQueue using guava's library I am having the following issue: , Use java.lang.Double perhaps?
code :
 val q: MinMaxPriorityQueue[java.lang.Double] = ...
Comparable is a raw type. References to generic type Comparable<T> should be parameterized

Comparable is a raw type. References to generic type Comparable<T> should be parameterized


By : Ahmed Aboshniba
Date : March 29 2020, 07:55 AM
Hope that helps There are several things wrong with your current scheme.
Comparator and Comparable are two different approaches to comparing objects. You are confusing the two. You are trying to store a function that does comparisons into the map. Later, you fetch the value from the map and try to compare it (the function) to a Comparator. This won't work, as you can't compare a function to anything except another function. You don't actually store a value anywhere; you are only storing a function. In your example, you store two different values to the same VARIABLE_NAME. Is that intentional?
code :
class Storable<T extends Comparable<T>> {
  private final T value;
  Storable(T value) {
    this.value = value;
  }
  int compareTo(Object other) {
    if ( value.getClass().equals(other.getClass()) ) {
      return value.compareTo( (T) other );
    }
    return -1;
  }
}
class StorableInt extends Storable<Integer> {
    StorableInt(Integer t) {
        super(t);
    }
}
class StorableString extends Storable<String> {
    StorableString(String s) {
        super(s);
    }
}
Map<String, Storable<?>>map = new HashMap<>();

map.put(variableName1, new StorableInt(13));
map.put(variableName2, new StorableString("string2"));

<T extends Comparable<T>> int compare( String key, T val ) {
  return map.get( key ).compareTo( val );
}
Scala generics type extends Comparable interface

Scala generics type extends Comparable interface


By : Lighty
Date : March 29 2020, 07:55 AM
will be helpful for those in need Consider alternative implementation using Ordering type class like so
code :
class A(val value: Int)
class B(value: Int) extends A(value)

class C[T](val value: T)

implicit val aOrdering = new Ordering[A] {
  def compare(a1: A, a2: A): Int = a1.value compare a2.value
}

implicit val bOrdering = new Ordering[B] {
  def compare(b1: B, b2: B): Int = b1.value compare b2.value
}

implicit class CompareToA[T <: A](`this`: T) {
  def compareTo(that: T)(implicit o: Ordering[T]): Int = o.compare(`this`, that)
}

implicit class CompareToC[T](`this`: C[T]) {
  def compareTo(that: C[T])(implicit o: Ordering[T]): Int = o.compare(`this`.value, that.value)
}
val b1 = new B(1)
val b2 = new B(2)
val bc1 = new C[B](b1)
val bc2 = new C[B](b2)
bc1.compareTo(bc2) // res3: Int = -1
How to implement Java interface that extends Comparable with no specific type in Scala?

How to implement Java interface that extends Comparable with no specific type in Scala?


By : user3395945
Date : March 29 2020, 07:55 AM
I wish did fix the issue. There is no direct way to do it. One way to make you code run against pre-java5 code, is to have Java bridge methods:
code :
public abstract class B implements A {
    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

object AFactory {
  def getA: A = new B {
    override def getSomething: String = "test"
  }
}
public abstract class B implements A {
    @Override
    public int compareTo(Object o) {
        return compareToBridge(o);
    }

    protected abstract int compareToBridge(Object o);
}

object AFactory {
  def getA: A = new B {
    override def getSomething: String = "test"

    override def compareToBridge(o: Any): Int = ???
  }
}
Java: Comparable implementation with Generics if comparable to two or more type of Objects

Java: Comparable implementation with Generics if comparable to two or more type of Objects


By : Zelalem Rufael
Date : March 29 2020, 07:55 AM
Hope this helps Normally all the types would have a common interface they all implement. It doesn't make sense to be comparable to lots of things which have nothing in common.
BTW: a.compareTo(b) == -b.compareTo(a) means you can't get too complicated with the types which you caompare to.
Related Posts Related Posts :
  • Assign generic method to variable in Scala
  • General Finite State Machine (Transducer) in Scala
  • What is the usage of a final var in Scala
  • Define Generic Types with String
  • Why there is a ClassCastException when isInstanceOf returns true on a scala type with wildcard parameter?
  • How to reaload scala application after code change using actors and sbt
  • akka non-blocking BoundedMailbox
  • Why are constructor parameters made into members for case classes?
  • Higher order tail recursive function needs to terminate early
  • How can I reusably filter based on type in Scala?
  • Why does Scala sbt update every time I start it from command prompt?
  • Recommended Scala io library
  • Thread-safely transforming a value in a mutable map
  • Why does chaining match expressions does not compile?
  • Ebean not persisting foreign keys
  • Difference between def m(p: T forSome {type T} and def m1(p:Any), is there any ? Explanation needed based on Scala Langu
  • macro does not find out enclosing vals
  • Spark : how to run spark file from spark shell
  • Flattening a list of lists to a set with exceptions in scala
  • flatMap implementation in Scala
  • Confused about a few lines code in a scala official document page
  • How to input parameters when running bash command with Scala
  • Location header is lost if max-redirects > 1
  • Controller Spec is using FakeApplication, but can't load test configuration
  • Scala code analyzer targets case variable names that are identical to the outer matched varables - "suspicous shado
  • Why does authorize directive execute after the code it's supposed to protect?
  • Does having a private constructor on a value class negate the benefits of a value class?
  • How to transform submitted json in Play 2.0?
  • Scala warning match may not be exhaustive
  • Pure not a member of objective Promise in PlayFramework
  • How to unmarshal POST params and JSON body in a single route?
  • Spark:How to use join method?
  • is client thread-safe in Twitter Finagle
  • Why is the method accepts only one argument?
  • Scala Play 2.3 Working with gCloud Storage - any libs to go async?
  • spray.io strange get/delete/detach directives behavior
  • SBT cannot resolve class declared in src/main/scala in a src/test/scala test class
  • Scala typeclass without function argument
  • Configuring actor behavior using typesafe Config and HOCON
  • Scalatra: Migrating Jersey Filters to Scalatra
  • Compilation error when using Scaldi
  • Scalac hanging in phase typer
  • how to have different source code when cross-compiling Scala with sbt? (changes in MurmurHash)
  • How to set different scalacOptions per Scala version when cross-compiling using Build.scala?
  • Possible Bug in JDBC?
  • Is there a Scala compiler flag to warn when tail recursion is applied without annotation?
  • scala case class put methods in companion object?
  • multiproject sbt doesn't generate file structure
  • Scala "multilevel" abstract class / abstract objects replacement
  • Scala, getting the type parameters of a KList as an HList
  • Why does Play refuse form reporting "Cannot resolve method apply with such signature: Missing arguments"?
  • How to split string with trailing empty strings in result?
  • Scala group by list of list and subtracts grouped values
  • Scala - Creating a function to produce Unary string or integer values
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org